use std::collections::BTreeMap;
use cypher_rs_zk::{
BinOp as CypherBinOp, CallClause as CypherCallClause, Clause,
CreateClause as CypherCreateClause, DeleteClause as CypherDeleteClause,
Direction as CypherDirection, Expr, FunctionArguments, Literal,
MatchClause as CypherMatchClause, MergeAction as CypherMergeAction,
MergeActionKind as CypherMergeActionKind, MergeClause as CypherMergeClause,
NodePattern as CypherNodePattern, Pattern as CypherPattern, RelPattern as CypherRelPattern,
ReturnClause, SetClause as CypherSetClause, SetItem as CypherSetItem, UnOp as CypherUnOp,
UnwindClause as CypherUnwindClause,
};
use crate::cypher::ast::{
ComparisonOperator, CreateRelationshipStatement, CreateStatement, DeleteStatement, Direction,
Expression, MatchClause, MergeAction, MergeBranch, MergeStatement, NodePattern, Operand,
OrderDirection, OrderItem, Pattern, PatternChain, Predicate, ProcedureCall, ProcedureYield,
PropertyPredicate, Query, RelationshipPattern, RemoveItem, RemoveStatement, ReturnExpression,
ReturnItem, ReturnProjection, RowCount, SetItem, SetStatement, Statement, StringOperator,
UnwindClause, WithProjection,
};
use crate::error::{Error, Result};
use crate::value::Value;
pub fn parse_statement(input: &str) -> Result<Statement> {
if find_top_level_keyword(input, "REMOVE").is_some() {
return parse_remove_statement(input).map(Statement::Remove);
}
let query = cypher_rs_zk::parse(input).map_err(|error| Error::Parse(error.to_string()))?;
build_statement(query.clauses)
}
#[allow(dead_code)]
pub fn parse_query(input: &str) -> Result<Query> {
let query = cypher_rs_zk::parse(input).map_err(|error| Error::Parse(error.to_string()))?;
QueryBuilder::default().build(query.clauses)
}
fn build_statement(clauses: Vec<Clause>) -> Result<Statement> {
let write_indexes = clauses
.iter()
.enumerate()
.filter_map(|(index, clause)| {
matches!(
clause,
Clause::Create(_) | Clause::Merge(_) | Clause::Set(_) | Clause::Delete(_)
)
.then_some(index)
})
.collect::<Vec<_>>();
let Some(&write_index) = write_indexes.first() else {
return QueryBuilder::default()
.build(clauses)
.map(Statement::Single);
};
if write_indexes.len() != 1 {
return Err(Error::UnsupportedWriteQuery(
"multiple write clauses in one query".to_string(),
));
}
let mut clauses = clauses;
let trailing = clauses.split_off(write_index + 1);
let write = clauses
.pop()
.ok_or_else(|| Error::Parse("write clause is missing".to_string()))?;
let matches = convert_write_prefix(clauses)?;
match write {
Clause::Create(create) => build_create_statement(matches, create, trailing),
Clause::Merge(merge_clause) => build_merge_statement(matches, merge_clause, trailing),
Clause::Set(set) => build_set_statement(matches, set, trailing),
Clause::Delete(delete) => build_delete_statement(matches, delete, trailing),
_ => unreachable!(),
}
}
fn build_create_statement(
matches: Vec<MatchClause>,
create: CypherCreateClause,
trailing: Vec<Clause>,
) -> Result<Statement> {
let returns = convert_write_return(trailing)?;
let mut patterns = create.patterns;
if patterns.len() != 1 {
return Err(Error::UnsupportedWriteQuery(
"CREATE currently supports one pattern".to_string(),
));
}
let pattern = convert_pattern(patterns.remove(0))?;
if pattern.chains.is_empty() {
if !matches.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"CREATE node after MATCH".to_string(),
));
}
return Ok(Statement::Create(CreateStatement {
node: pattern.start,
returns,
}));
}
if matches.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"relationship CREATE without MATCH".to_string(),
));
}
Ok(Statement::CreateRelationship(CreateRelationshipStatement {
matches,
pattern,
returns,
}))
}
fn build_merge_statement(
matches: Vec<MatchClause>,
merge_clause: CypherMergeClause,
trailing: Vec<Clause>,
) -> Result<Statement> {
let returns = convert_write_return(trailing)?;
let pattern = convert_pattern(merge_clause.pattern)?;
let actions = merge_clause
.actions
.into_iter()
.map(convert_merge_action)
.collect::<Result<Vec<_>>>()?;
if pattern.chains.is_empty() {
if !matches.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"MERGE node after MATCH".to_string(),
));
}
return Ok(Statement::Merge(MergeStatement::Node {
node: pattern.start,
actions,
returns,
}));
}
if matches.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"relationship MERGE without MATCH".to_string(),
));
}
Ok(Statement::Merge(MergeStatement::Relationship {
matches,
pattern,
actions,
returns,
}))
}
fn build_set_statement(
matches: Vec<MatchClause>,
set: CypherSetClause,
trailing: Vec<Clause>,
) -> Result<Statement> {
if matches.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"SET without MATCH".to_string(),
));
}
Ok(Statement::Set(SetStatement {
matches,
items: set
.items
.into_iter()
.map(convert_set_item)
.collect::<Result<Vec<_>>>()?,
returns: convert_write_return(trailing)?,
}))
}
fn build_delete_statement(
matches: Vec<MatchClause>,
delete: CypherDeleteClause,
trailing: Vec<Clause>,
) -> Result<Statement> {
if matches.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"DELETE without MATCH".to_string(),
));
}
if !trailing.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"clauses after DELETE".to_string(),
));
}
let variables = delete
.expressions
.into_iter()
.map(|expression| match expression {
Expr::Variable(variable) => Ok(variable),
_ => Err(Error::UnsupportedWriteQuery(
"DELETE currently supports variables".to_string(),
)),
})
.collect::<Result<Vec<_>>>()?;
Ok(Statement::Delete(DeleteStatement {
matches,
variables,
detach: delete.detach,
}))
}
fn convert_write_prefix(clauses: Vec<Clause>) -> Result<Vec<MatchClause>> {
let mut matches = Vec::<MatchClause>::new();
for clause in clauses {
match clause {
Clause::Match(clause) => matches.push(convert_match(clause)?),
Clause::Where(expression) => {
let clause = matches.last_mut().ok_or_else(|| {
Error::Parse("WHERE must immediately follow MATCH".to_string())
})?;
if clause.predicate.is_some() {
return Err(Error::Parse(
"MATCH contains multiple WHERE clauses".to_string(),
));
}
clause.predicate = Some(convert_predicate(expression)?);
}
_ => {
return Err(Error::UnsupportedWriteQuery(
"write clauses currently support a MATCH prefix".to_string(),
));
}
}
}
Ok(matches)
}
fn convert_write_return(clauses: Vec<Clause>) -> Result<ReturnProjection> {
let mut clauses = clauses.into_iter();
match (clauses.next(), clauses.next()) {
(None, None) => Ok(ReturnProjection::Items(Vec::new())),
(Some(Clause::Return(clause)), None) => convert_projection(clause),
_ => Err(Error::UnsupportedWriteQuery(
"write clause may only be followed by RETURN".to_string(),
)),
}
}
fn convert_merge_action(action: CypherMergeAction) -> Result<MergeAction> {
Ok(MergeAction {
branch: match action.kind {
CypherMergeActionKind::OnCreate => MergeBranch::OnCreate,
CypherMergeActionKind::OnMatch => MergeBranch::OnMatch,
},
items: action
.items
.into_iter()
.map(convert_set_item)
.collect::<Result<Vec<_>>>()?,
})
}
fn convert_set_item(item: CypherSetItem) -> Result<SetItem> {
match item {
CypherSetItem::Property { property, value } => {
let Expr::Property { base, key } = property else {
return Err(Error::Parse("SET property target is invalid".to_string()));
};
let Expr::Variable(variable) = *base else {
return Err(Error::UnsupportedWriteQuery(
"nested SET property targets".to_string(),
));
};
Ok(SetItem::Property {
variable,
key,
expression: convert_expression(value)?,
})
}
CypherSetItem::AllProperties { variable, value } => Ok(SetItem::PropertiesReplace {
variable,
expression: convert_expression(value)?,
}),
CypherSetItem::MergeProperties { variable, value } => Ok(SetItem::PropertiesMerge {
variable,
expression: convert_expression(value)?,
}),
CypherSetItem::Labels { variable, labels } => Ok(SetItem::Label { variable, labels }),
}
}
fn parse_remove_statement(input: &str) -> Result<RemoveStatement> {
let remove_index = find_top_level_keyword(input, "REMOVE")
.ok_or_else(|| Error::Parse("REMOVE clause is missing".to_string()))?;
let prefix = input[..remove_index].trim();
let remove_tail = input[remove_index + "REMOVE".len()..].trim();
let return_index = find_top_level_keyword(remove_tail, "RETURN");
let (item_text, return_text) = match return_index {
Some(index) => (remove_tail[..index].trim(), Some(&remove_tail[index..])),
None => (remove_tail, None),
};
if prefix.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"REMOVE without MATCH".to_string(),
));
}
if item_text.is_empty() {
return Err(Error::Parse("REMOVE clause has no items".to_string()));
}
let query = cypher_rs_zk::parse(prefix).map_err(|error| Error::Parse(error.to_string()))?;
let matches = convert_write_prefix(query.clauses)?;
if matches.is_empty() {
return Err(Error::UnsupportedWriteQuery(
"REMOVE without MATCH".to_string(),
));
}
let items = split_top_level(item_text, ',')
.into_iter()
.map(convert_remove_item)
.collect::<Result<Vec<_>>>()?;
let returns = match return_text {
Some(return_text) => {
let query = cypher_rs_zk::parse(return_text)
.map_err(|error| Error::Parse(error.to_string()))?;
convert_write_return(query.clauses)?
}
None => ReturnProjection::Items(Vec::new()),
};
Ok(RemoveStatement {
matches,
items,
returns,
})
}
fn convert_remove_item(item: &str) -> Result<RemoveItem> {
let item = item.trim();
if let Some((variable, key)) = item.split_once('.') {
if key.contains('.') {
return Err(Error::UnsupportedWriteQuery(
"nested REMOVE property targets".to_string(),
));
}
return Ok(RemoveItem::Property {
variable: parse_remove_identifier(variable)?,
key: parse_remove_identifier(key)?,
});
}
let mut identifiers = item.split(':').map(parse_remove_identifier);
let variable = identifiers
.next()
.ok_or_else(|| Error::Parse("REMOVE item is empty".to_string()))??;
let labels = identifiers.collect::<Result<Vec<_>>>()?;
if labels.is_empty() {
return Err(Error::Parse(format!(
"REMOVE item `{item}` must be a property or label target"
)));
}
Ok(RemoveItem::Label { variable, labels })
}
fn parse_remove_identifier(input: &str) -> Result<String> {
let input = input.trim();
if input.starts_with('`') && input.ends_with('`') && input.len() > 2 {
return Ok(input[1..input.len() - 1].replace("``", "`"));
}
let mut characters = input.chars();
let Some(first) = characters.next() else {
return Err(Error::Parse("REMOVE identifier is empty".to_string()));
};
if !(first.is_ascii_alphabetic() || first == '_')
|| !characters.all(|character| character.is_ascii_alphanumeric() || character == '_')
{
return Err(Error::Parse(format!("invalid REMOVE identifier `{input}`")));
}
Ok(input.to_string())
}
fn split_top_level(input: &str, separator: char) -> Vec<&str> {
let mut parts = Vec::new();
let mut start = 0;
let mut depth = 0usize;
let mut quote = None;
let mut escaped = false;
for (index, character) in input.char_indices() {
if let Some(active_quote) = quote {
if escaped {
escaped = false;
} else if character == '\\' {
escaped = true;
} else if character == active_quote {
quote = None;
}
continue;
}
match character {
'\'' | '"' | '`' => quote = Some(character),
'(' | '[' | '{' => depth += 1,
')' | ']' | '}' => depth = depth.saturating_sub(1),
_ if character == separator && depth == 0 => {
parts.push(input[start..index].trim());
start = index + character.len_utf8();
}
_ => {}
}
}
parts.push(input[start..].trim());
parts
}
fn find_top_level_keyword(input: &str, keyword: &str) -> Option<usize> {
let mut depth = 0usize;
let mut quote = None;
let mut escaped = false;
for (index, character) in input.char_indices() {
if let Some(active_quote) = quote {
if escaped {
escaped = false;
} else if character == '\\' {
escaped = true;
} else if character == active_quote {
quote = None;
}
continue;
}
match character {
'\'' | '"' | '`' => quote = Some(character),
'(' | '[' | '{' => depth += 1,
')' | ']' | '}' => depth = depth.saturating_sub(1),
_ if depth == 0 && keyword_at(input, index, keyword) => return Some(index),
_ => {}
}
}
None
}
fn keyword_at(input: &str, index: usize, keyword: &str) -> bool {
let Some(candidate) = input.get(index..index + keyword.len()) else {
return false;
};
if !candidate.eq_ignore_ascii_case(keyword) {
return false;
}
let before = input[..index].chars().next_back();
let after = input[index + keyword.len()..].chars().next();
!before.is_some_and(is_identifier_continue) && !after.is_some_and(is_identifier_continue)
}
fn is_identifier_continue(character: char) -> bool {
character.is_ascii_alphanumeric() || character == '_'
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Scope {
#[default]
Initial,
AfterWith,
AfterSecondWith,
Returned,
}
#[derive(Clone, Copy)]
enum MatchTarget {
Initial,
PostUnwind,
PostProcedure,
PostWith,
PostWithProcedure,
PostSecondWith,
PostSecondWithProcedure,
}
#[derive(Clone, Copy)]
enum PredicateTarget {
Match(MatchTarget, usize),
With(Scope),
}
#[derive(Default)]
struct QueryBuilder {
scope: Scope,
initial_matches: Vec<MatchClause>,
unwinds: Vec<UnwindClause>,
post_unwind_matches: Vec<MatchClause>,
procedure_calls: Vec<ProcedureCall>,
post_procedure_unwinds: Vec<UnwindClause>,
post_procedure_matches: Vec<MatchClause>,
saw_procedure_call: bool,
post_with_unwinds: Vec<UnwindClause>,
post_with_matches: Vec<MatchClause>,
post_with_procedure_calls: Vec<ProcedureCall>,
post_with_procedure_unwinds: Vec<UnwindClause>,
post_with_procedure_matches: Vec<MatchClause>,
post_second_with_unwinds: Vec<UnwindClause>,
post_second_with_matches: Vec<MatchClause>,
post_second_with_procedure_calls: Vec<ProcedureCall>,
post_second_with_procedure_unwinds: Vec<UnwindClause>,
post_second_with_procedure_matches: Vec<MatchClause>,
with: Option<WithProjection>,
with_predicate: Option<Predicate>,
with_order_by: Vec<OrderItem>,
with_skip: Option<RowCount>,
with_limit: Option<RowCount>,
second_with: Option<WithProjection>,
second_with_predicate: Option<Predicate>,
second_with_order_by: Vec<OrderItem>,
second_with_skip: Option<RowCount>,
second_with_limit: Option<RowCount>,
returns: Option<ReturnProjection>,
distinct: bool,
order_by: Vec<OrderItem>,
skip: Option<RowCount>,
limit: Option<RowCount>,
predicate_target: Option<PredicateTarget>,
}
impl QueryBuilder {
fn build(mut self, clauses: Vec<Clause>) -> Result<Query> {
for clause in clauses {
self.push(clause)?;
}
let implicit_return = self.returns.is_none();
if implicit_return
&& self.procedure_calls.is_empty()
&& self.post_with_procedure_calls.is_empty()
&& self.post_second_with_procedure_calls.is_empty()
{
return Err(Error::Parse(
"RETURN clause is missing projection".to_string(),
));
}
let returns = self
.returns
.take()
.unwrap_or_else(|| ReturnProjection::Items(Vec::new()));
let has_initial_match = !self.initial_matches.is_empty();
let first_match = self
.initial_matches
.first()
.cloned()
.unwrap_or_else(empty_match_clause);
Ok(Query {
has_initial_match,
optional_match: first_match.optional_match,
pattern: first_match.pattern,
patterns: first_match.patterns,
predicate: first_match.predicate,
extra_matches: self.initial_matches.into_iter().skip(1).collect(),
unwinds: self.unwinds,
post_unwind_matches: self.post_unwind_matches,
procedure_calls: self.procedure_calls,
post_procedure_unwinds: self.post_procedure_unwinds,
post_procedure_matches: self.post_procedure_matches,
with: self.with,
with_predicate: self.with_predicate,
with_order_by: self.with_order_by,
with_skip: self.with_skip,
with_limit: self.with_limit,
post_with_unwinds: self.post_with_unwinds,
post_with_matches: self.post_with_matches,
post_with_procedure_calls: self.post_with_procedure_calls,
post_with_procedure_unwinds: self.post_with_procedure_unwinds,
post_with_procedure_matches: self.post_with_procedure_matches,
post_with_with: self.second_with,
post_with_with_predicate: self.second_with_predicate,
post_with_with_order_by: self.second_with_order_by,
post_with_with_skip: self.second_with_skip,
post_with_with_limit: self.second_with_limit,
post_with_with_unwinds: self.post_second_with_unwinds,
post_with_with_matches: self.post_second_with_matches,
post_with_with_procedure_calls: self.post_second_with_procedure_calls,
post_with_with_procedure_unwinds: self.post_second_with_procedure_unwinds,
post_with_with_procedure_matches: self.post_second_with_procedure_matches,
post_with_with_calls: Vec::new(),
calls: Vec::new(),
post_call_unwinds: Vec::new(),
post_call_matches: Vec::new(),
post_call_with: None,
post_call_with_predicate: None,
post_call_with_order_by: Vec::new(),
post_call_with_skip: None,
post_call_with_limit: None,
post_call_with_unwinds: Vec::new(),
post_call_with_matches: Vec::new(),
distinct: self.distinct,
returns,
implicit_return,
order_by: self.order_by,
skip: self.skip,
limit: self.limit,
})
}
fn push(&mut self, clause: Clause) -> Result<()> {
match clause {
Clause::Match(clause) => self.push_match(clause),
Clause::Where(expression) => self.push_where(expression),
Clause::With(clause) => self.push_with(clause),
Clause::Return(clause) => self.push_return(clause),
Clause::OrderBy(items) => self.push_order_by(items),
Clause::Skip(expression) => self.push_row_count(expression, false),
Clause::Limit(expression) => self.push_row_count(expression, true),
Clause::Unwind(clause) => self.push_unwind(clause),
Clause::Create(_) => Err(Error::UnsupportedWriteQuery("CREATE".to_string())),
Clause::Merge(_) => Err(Error::UnsupportedWriteQuery("MERGE".to_string())),
Clause::Set(_) => Err(Error::UnsupportedWriteQuery("SET".to_string())),
Clause::Remove(_) => Err(Error::UnsupportedWriteQuery("REMOVE".to_string())),
Clause::Delete(_) => Err(Error::UnsupportedWriteQuery("DELETE".to_string())),
Clause::Foreach(_) => Err(Error::UnsupportedWriteQuery("FOREACH".to_string())),
Clause::SchemaCommand(_) => Err(Error::UnsupportedQueryFeature(
"schema commands".to_string(),
)),
Clause::Start(_) => Err(Error::UnsupportedQueryFeature("START".to_string())),
Clause::LoadCsv(_) => Err(Error::UnsupportedQueryFeature("LOAD CSV".to_string())),
Clause::Call(clause) => self.push_procedure_call(clause),
Clause::Union(_) => Err(Error::UnsupportedQueryFeature("UNION".to_string())),
}
}
fn push_match(&mut self, clause: CypherMatchClause) -> Result<()> {
if self.scope == Scope::Returned {
return Err(Error::Parse("MATCH cannot appear after RETURN".to_string()));
}
let clause = convert_match(clause)?;
let (target, matches) = match (self.scope, self.saw_procedure_call) {
(Scope::Initial, true) => {
(MatchTarget::PostProcedure, &mut self.post_procedure_matches)
}
(Scope::AfterWith, true) => (
MatchTarget::PostWithProcedure,
&mut self.post_with_procedure_matches,
),
(Scope::AfterSecondWith, true) => (
MatchTarget::PostSecondWithProcedure,
&mut self.post_second_with_procedure_matches,
),
(Scope::Initial, false) if self.unwinds.is_empty() => {
(MatchTarget::Initial, &mut self.initial_matches)
}
(Scope::Initial, false) => (MatchTarget::PostUnwind, &mut self.post_unwind_matches),
(Scope::AfterWith, false) => (MatchTarget::PostWith, &mut self.post_with_matches),
(Scope::AfterSecondWith, false) => (
MatchTarget::PostSecondWith,
&mut self.post_second_with_matches,
),
(Scope::Returned, _) => unreachable!(),
};
matches.push(clause);
self.predicate_target = Some(PredicateTarget::Match(target, matches.len() - 1));
Ok(())
}
fn push_unwind(&mut self, clause: CypherUnwindClause) -> Result<()> {
let unwind = UnwindClause {
expression: convert_expression(clause.expr)?,
variable: clause.alias,
};
match (self.scope, self.saw_procedure_call) {
(Scope::Initial, true) if !self.post_procedure_matches.is_empty() => {
return Err(Error::UnsupportedQueryFeature(
"UNWIND after a post-procedure MATCH".to_string(),
));
}
(Scope::Initial, true) => self.post_procedure_unwinds.push(unwind),
(Scope::AfterWith, true) if !self.post_with_procedure_matches.is_empty() => {
return Err(Error::UnsupportedQueryFeature(
"UNWIND after a post-procedure MATCH in a WITH scope".to_string(),
));
}
(Scope::AfterWith, true) => self.post_with_procedure_unwinds.push(unwind),
(Scope::AfterSecondWith, true)
if !self.post_second_with_procedure_matches.is_empty() =>
{
return Err(Error::UnsupportedQueryFeature(
"UNWIND after a post-procedure MATCH in a second WITH scope".to_string(),
));
}
(Scope::AfterSecondWith, true) => self.post_second_with_procedure_unwinds.push(unwind),
(Scope::Initial, false) if !self.post_unwind_matches.is_empty() => {
return Err(Error::UnsupportedQueryFeature(
"UNWIND after a post-UNWIND MATCH".to_string(),
));
}
(Scope::Initial, false) => self.unwinds.push(unwind),
(Scope::AfterWith, false) if !self.post_with_matches.is_empty() => {
return Err(Error::UnsupportedQueryFeature(
"UNWIND after MATCH in a WITH scope".to_string(),
));
}
(Scope::AfterWith, false) => self.post_with_unwinds.push(unwind),
(Scope::AfterSecondWith, false) if !self.post_second_with_matches.is_empty() => {
return Err(Error::UnsupportedQueryFeature(
"UNWIND after MATCH in a second WITH scope".to_string(),
));
}
(Scope::AfterSecondWith, false) => self.post_second_with_unwinds.push(unwind),
(Scope::Returned, _) => {
return Err(Error::Parse(
"UNWIND cannot appear after RETURN".to_string(),
));
}
}
self.predicate_target = None;
Ok(())
}
fn push_procedure_call(&mut self, clause: CypherCallClause) -> Result<()> {
if self.returns.is_some() {
return Err(Error::Parse(
"procedure CALL cannot appear after RETURN".to_string(),
));
}
let has_post_procedure_clause = match self.scope {
Scope::Initial => {
!self.post_procedure_unwinds.is_empty() || !self.post_procedure_matches.is_empty()
}
Scope::AfterWith => {
!self.post_with_procedure_unwinds.is_empty()
|| !self.post_with_procedure_matches.is_empty()
}
Scope::AfterSecondWith => {
!self.post_second_with_procedure_unwinds.is_empty()
|| !self.post_second_with_procedure_matches.is_empty()
}
Scope::Returned => false,
};
if has_post_procedure_clause {
return Err(Error::UnsupportedQueryFeature(
"procedure CALL after a post-procedure MATCH or UNWIND".to_string(),
));
}
let call = ProcedureCall {
name: clause.name,
arguments: clause
.arguments
.into_iter()
.map(convert_expression)
.collect::<Result<Vec<_>>>()?,
yields: clause
.yields
.into_iter()
.map(|item| ProcedureYield {
field: item.field,
alias: item.alias,
})
.collect(),
predicate: clause.predicate.map(convert_predicate).transpose()?,
};
match self.scope {
Scope::Initial => self.procedure_calls.push(call),
Scope::AfterWith => self.post_with_procedure_calls.push(call),
Scope::AfterSecondWith => self.post_second_with_procedure_calls.push(call),
Scope::Returned => unreachable!(),
}
self.saw_procedure_call = true;
self.predicate_target = None;
Ok(())
}
fn push_where(&mut self, expression: Expr) -> Result<()> {
let predicate = convert_predicate(expression)?;
match self.predicate_target.take() {
Some(PredicateTarget::Match(target, index)) => {
let matches = match target {
MatchTarget::Initial => &mut self.initial_matches,
MatchTarget::PostUnwind => &mut self.post_unwind_matches,
MatchTarget::PostProcedure => &mut self.post_procedure_matches,
MatchTarget::PostWith => &mut self.post_with_matches,
MatchTarget::PostWithProcedure => &mut self.post_with_procedure_matches,
MatchTarget::PostSecondWith => &mut self.post_second_with_matches,
MatchTarget::PostSecondWithProcedure => {
&mut self.post_second_with_procedure_matches
}
};
matches[index].predicate = Some(predicate);
}
Some(PredicateTarget::With(Scope::AfterWith)) => {
self.with_predicate = Some(predicate);
}
Some(PredicateTarget::With(Scope::AfterSecondWith)) => {
self.second_with_predicate = Some(predicate);
}
_ => {
return Err(Error::Parse(
"WHERE must immediately follow MATCH or WITH".to_string(),
));
}
}
Ok(())
}
fn push_with(&mut self, clause: ReturnClause) -> Result<()> {
let projection = WithProjection {
distinct: clause.distinct,
projection: convert_projection(clause)?,
};
match self.scope {
Scope::Initial => {
self.with = Some(projection);
self.scope = Scope::AfterWith;
}
Scope::AfterWith => {
self.second_with = Some(projection);
self.scope = Scope::AfterSecondWith;
}
Scope::AfterSecondWith => {
return Err(Error::UnsupportedQueryFeature(
"more than two WITH clauses".to_string(),
));
}
Scope::Returned => {
return Err(Error::Parse("WITH cannot appear after RETURN".to_string()));
}
}
self.saw_procedure_call = false;
self.predicate_target = Some(PredicateTarget::With(self.scope));
Ok(())
}
fn push_return(&mut self, clause: ReturnClause) -> Result<()> {
if self.returns.is_some() {
return Err(Error::Parse(
"query contains multiple RETURN clauses".to_string(),
));
}
self.distinct = clause.distinct;
self.returns = Some(convert_projection(clause)?);
self.scope = Scope::Returned;
self.predicate_target = None;
Ok(())
}
fn push_order_by(&mut self, items: Vec<cypher_rs_zk::OrderItem>) -> Result<()> {
let items = items
.into_iter()
.map(|item| {
Ok(OrderItem {
item: convert_return_item(item.expr, None)?,
direction: if item.desc {
OrderDirection::Descending
} else {
OrderDirection::Ascending
},
})
})
.collect::<Result<Vec<_>>>()?;
match self.scope {
Scope::AfterWith => self.with_order_by = items,
Scope::AfterSecondWith => self.second_with_order_by = items,
Scope::Returned => self.order_by = items,
Scope::Initial => {
return Err(Error::Parse(
"ORDER BY requires a preceding WITH or RETURN".to_string(),
));
}
}
self.predicate_target = None;
Ok(())
}
fn push_row_count(&mut self, expression: Expr, is_limit: bool) -> Result<()> {
let row_count = convert_row_count(expression)?;
let target = match (self.scope, is_limit) {
(Scope::AfterWith, false) => &mut self.with_skip,
(Scope::AfterWith, true) => &mut self.with_limit,
(Scope::AfterSecondWith, false) => &mut self.second_with_skip,
(Scope::AfterSecondWith, true) => &mut self.second_with_limit,
(Scope::Returned, false) => &mut self.skip,
(Scope::Returned, true) => &mut self.limit,
(Scope::Initial, _) => {
return Err(Error::Parse(
"SKIP or LIMIT requires a preceding WITH or RETURN".to_string(),
));
}
};
*target = Some(row_count);
self.predicate_target = None;
Ok(())
}
}
fn convert_match(clause: CypherMatchClause) -> Result<MatchClause> {
let patterns = clause
.patterns
.into_iter()
.map(convert_pattern)
.collect::<Result<Vec<_>>>()?;
let pattern = patterns
.first()
.cloned()
.ok_or_else(|| Error::Parse("MATCH clause has no patterns".to_string()))?;
Ok(MatchClause {
optional_match: clause.optional,
pattern,
patterns,
predicate: None,
})
}
fn convert_pattern(pattern: CypherPattern) -> Result<Pattern> {
let mut left_variable = pattern.anchor.var.clone();
let start = convert_node(pattern.anchor)?;
let mut chains = Vec::with_capacity(pattern.chain.len());
for chain in pattern.chain {
let node_variable = chain.node.var.clone();
chains.push(PatternChain {
left_variable,
relationship: convert_relationship(chain.rel)?,
node: convert_node(chain.node)?,
});
left_variable = node_variable;
}
Ok(Pattern {
variable: None,
shortest_path: None,
start,
chains,
})
}
fn convert_node(node: CypherNodePattern) -> Result<NodePattern> {
Ok(NodePattern {
variable: node.var,
labels: node.labels,
properties: convert_properties(node.properties)?,
})
}
fn convert_relationship(relationship: CypherRelPattern) -> Result<RelationshipPattern> {
Ok(RelationshipPattern {
variable: relationship.var,
types: relationship.types,
direction: match relationship.direction {
CypherDirection::Outgoing => Direction::Outgoing,
CypherDirection::Incoming => Direction::Incoming,
CypherDirection::Undirected => Direction::Undirected,
},
variable_length: false,
min_hops: 1,
max_hops: Some(1),
properties: convert_properties(relationship.properties)?,
})
}
fn convert_properties(properties: Vec<(String, Expr)>) -> Result<Vec<PropertyPredicate>> {
properties
.into_iter()
.map(|(key, expression)| {
Ok(PropertyPredicate {
key,
expression: convert_expression(expression)?,
})
})
.collect()
}
fn convert_projection(clause: ReturnClause) -> Result<ReturnProjection> {
clause
.items
.into_iter()
.map(|item| convert_return_item(item.expr, item.alias))
.collect::<Result<Vec<_>>>()
.map(ReturnProjection::Items)
}
fn convert_return_item(expression: Expr, alias: Option<String>) -> Result<ReturnItem> {
let expression = match expression {
Expr::Variable(variable) => ReturnExpression::Variable(variable),
Expr::FunctionCall {
name,
arguments: FunctionArguments::Expressions(arguments),
..
} if name.eq_ignore_ascii_case("elementId") => {
let [Expr::Variable(variable)] = arguments.as_slice() else {
return Err(Error::Validation(
"elementId() requires one node or relationship variable".to_owned(),
));
};
ReturnExpression::ElementId(variable.clone())
}
Expr::Property { base, key } => match *base {
Expr::Variable(variable) => ReturnExpression::Property { variable, key },
base => ReturnExpression::Scalar(convert_expression(Expr::Property {
base: Box::new(base),
key,
})?),
},
expression => ReturnExpression::Scalar(convert_expression(expression)?),
};
Ok(ReturnItem { expression, alias })
}
fn convert_expression(expression: Expr) -> Result<Expression> {
match expression {
Expr::Literal(literal) => Ok(Expression::Literal(convert_literal(literal))),
Expr::List(items) => items
.into_iter()
.map(convert_expression)
.collect::<Result<Vec<_>>>()
.map(Expression::List),
Expr::Map(entries) => entries
.into_iter()
.map(|(key, value)| Ok((key, convert_expression(value)?)))
.collect::<Result<BTreeMap<_, _>>>()
.map(Expression::Map),
Expr::Variable(variable) => Ok(Expression::Operand(Operand::Variable(variable))),
Expr::Param(parameter) => Ok(Expression::Parameter(parameter)),
Expr::FunctionCall {
name,
arguments: FunctionArguments::Expressions(arguments),
..
} if name.eq_ignore_ascii_case("elementId") => {
let [Expr::Variable(variable)] = arguments.as_slice() else {
return Err(Error::Validation(
"elementId() requires one node or relationship variable".to_owned(),
));
};
Ok(Expression::Operand(Operand::Property {
variable: variable.clone(),
key: "__littlegraph_element_id".to_owned(),
}))
}
Expr::Property { base, key } => match *base {
Expr::Variable(variable) => {
Ok(Expression::Operand(Operand::Property { variable, key }))
}
_ => Err(Error::UnsupportedQueryFeature(
"property access on a non-variable expression".to_string(),
)),
},
Expr::Binary { op, lhs, rhs } if is_predicate_binary(op) => Ok(Expression::Predicate(
Box::new(convert_binary_predicate(op, *lhs, *rhs)?),
)),
Expr::Binary { op, lhs, rhs } => {
let lhs = Box::new(convert_expression(*lhs)?);
let rhs = Box::new(convert_expression(*rhs)?);
match op {
CypherBinOp::Add => Ok(Expression::Add(lhs, rhs)),
CypherBinOp::Sub => Ok(Expression::Subtract(lhs, rhs)),
CypherBinOp::Mul => Ok(Expression::Multiply(lhs, rhs)),
CypherBinOp::Div => Ok(Expression::Divide(lhs, rhs)),
CypherBinOp::Mod => Ok(Expression::Modulo(lhs, rhs)),
_ => unreachable!(),
}
}
Expr::Unary { op, operand } => match op {
CypherUnOp::Pos => convert_expression(*operand),
CypherUnOp::Neg => Ok(Expression::Subtract(
Box::new(Expression::Literal(Value::Integer(0))),
Box::new(convert_expression(*operand)?),
)),
CypherUnOp::Not | CypherUnOp::IsNull | CypherUnOp::IsNotNull => Ok(
Expression::Predicate(Box::new(convert_unary_predicate(op, *operand)?)),
),
},
expression => Err(Error::UnsupportedQueryFeature(format!(
"expression `{expression:?}`"
))),
}
}
fn convert_predicate(expression: Expr) -> Result<Predicate> {
match expression {
Expr::Binary { op, lhs, rhs } if is_predicate_binary(op) => {
convert_binary_predicate(op, *lhs, *rhs)
}
Expr::Unary { op, operand }
if matches!(
op,
CypherUnOp::Not | CypherUnOp::IsNull | CypherUnOp::IsNotNull
) =>
{
convert_unary_predicate(op, *operand)
}
expression => Ok(Predicate::Boolean(convert_expression(expression)?)),
}
}
fn convert_binary_predicate(op: CypherBinOp, lhs: Expr, rhs: Expr) -> Result<Predicate> {
match op {
CypherBinOp::And => Ok(Predicate::And(
Box::new(convert_predicate(lhs)?),
Box::new(convert_predicate(rhs)?),
)),
CypherBinOp::Or => Ok(Predicate::Or(
Box::new(convert_predicate(lhs)?),
Box::new(convert_predicate(rhs)?),
)),
CypherBinOp::In => Ok(Predicate::In {
item: convert_expression(lhs)?,
list: convert_expression(rhs)?,
}),
CypherBinOp::StartsWith | CypherBinOp::EndsWith | CypherBinOp::Contains => {
let operator = match op {
CypherBinOp::StartsWith => StringOperator::StartsWith,
CypherBinOp::EndsWith => StringOperator::EndsWith,
CypherBinOp::Contains => StringOperator::Contains,
_ => unreachable!(),
};
Ok(Predicate::StringMatch {
left: convert_expression(lhs)?,
operator,
right: convert_expression(rhs)?,
})
}
CypherBinOp::Eq
| CypherBinOp::Neq
| CypherBinOp::Lt
| CypherBinOp::Lte
| CypherBinOp::Gt
| CypherBinOp::Gte => {
let operator = match op {
CypherBinOp::Eq => ComparisonOperator::Equal,
CypherBinOp::Neq => ComparisonOperator::NotEqual,
CypherBinOp::Lt => ComparisonOperator::LessThan,
CypherBinOp::Lte => ComparisonOperator::LessThanOrEqual,
CypherBinOp::Gt => ComparisonOperator::GreaterThan,
CypherBinOp::Gte => ComparisonOperator::GreaterThanOrEqual,
_ => unreachable!(),
};
Ok(Predicate::Comparison {
left: convert_expression(lhs)?,
operator,
right: convert_expression(rhs)?,
})
}
_ => Err(Error::Parse("expected a predicate expression".to_string())),
}
}
fn convert_unary_predicate(op: CypherUnOp, operand: Expr) -> Result<Predicate> {
match op {
CypherUnOp::Not => Ok(Predicate::Not(Box::new(convert_predicate(operand)?))),
CypherUnOp::IsNull => Ok(Predicate::IsNull(convert_expression(operand)?)),
CypherUnOp::IsNotNull => Ok(Predicate::IsNotNull(convert_expression(operand)?)),
CypherUnOp::Pos | CypherUnOp::Neg => {
Err(Error::Parse("expected a predicate expression".to_string()))
}
}
}
fn is_predicate_binary(op: CypherBinOp) -> bool {
matches!(
op,
CypherBinOp::Eq
| CypherBinOp::Neq
| CypherBinOp::Lt
| CypherBinOp::Lte
| CypherBinOp::Gt
| CypherBinOp::Gte
| CypherBinOp::And
| CypherBinOp::Or
| CypherBinOp::In
| CypherBinOp::StartsWith
| CypherBinOp::EndsWith
| CypherBinOp::Contains
)
}
fn convert_row_count(expression: Expr) -> Result<RowCount> {
match expression {
Expr::Literal(Literal::Int(value)) => Ok(RowCount::Literal(value)),
Expr::Param(parameter) => Ok(RowCount::Parameter(parameter)),
expression => Ok(RowCount::Expression(convert_expression(expression)?)),
}
}
fn convert_literal(literal: Literal) -> Value {
match literal {
Literal::Int(value) => Value::Integer(value),
Literal::Float(value) => Value::Float(value),
Literal::String(value) => Value::String(value),
Literal::Bool(value) => Value::Boolean(value),
Literal::Null => Value::Null,
}
}
fn empty_match_clause() -> MatchClause {
let pattern = Pattern {
variable: None,
shortest_path: None,
start: NodePattern {
variable: None,
labels: Vec::new(),
properties: Vec::new(),
},
chains: Vec::new(),
};
MatchClause {
optional_match: false,
pattern: pattern.clone(),
patterns: vec![pattern],
predicate: None,
}
}
#[cfg(test)]
mod tests {
use super::{parse_query, parse_statement};
use crate::cypher::ast::{
Expression, Operand, Predicate, ReturnExpression, ReturnProjection, Statement,
};
fn return_items(query: &crate::cypher::ast::Query) -> &[crate::cypher::ast::ReturnItem] {
match &query.returns {
ReturnProjection::Items(items) => items,
ReturnProjection::Star => panic!("expected explicit return items"),
}
}
#[test]
fn converts_cypher_rs_patterns_and_predicates() {
let query = parse_query(
"MATCH (u:User {active: true})-[:FOLLOWS]->(f) \
WHERE u.id = $id AND f.name STARTS WITH 'A' RETURN f.name AS name",
)
.expect("parse query");
assert_eq!(query.pattern.start.variable.as_deref(), Some("u"));
assert_eq!(query.pattern.chains.len(), 1);
assert!(matches!(query.predicate, Some(Predicate::And(_, _))));
let ReturnExpression::Property { variable, key } = &return_items(&query)[0].expression
else {
panic!("expected property return")
};
assert_eq!((variable.as_str(), key.as_str()), ("f", "name"));
}
#[test]
fn converts_arithmetic_and_collections() {
let query = parse_query("RETURN 1 + 2 * 3 AS n, [1, $x] AS xs").expect("parse query");
let items = return_items(&query);
assert!(matches!(
items[0].expression,
ReturnExpression::Scalar(Expression::Add(_, _))
));
assert!(matches!(
items[1].expression,
ReturnExpression::Scalar(Expression::List(_))
));
}
#[test]
fn attaches_where_to_with_scope() {
let query =
parse_query("MATCH (u:User) WITH u.name AS name WHERE name = 'Alice' RETURN name")
.expect("parse query");
assert!(matches!(
query.with_predicate,
Some(Predicate::Comparison {
left: Expression::Operand(Operand::Variable(_)),
..
})
));
}
#[test]
fn parses_remove_with_return_projection() {
let Statement::Remove(remove) =
parse_statement("MATCH (n:User) REMOVE n.active RETURN n.active")
.expect("parse REMOVE RETURN")
else {
panic!("expected REMOVE statement");
};
assert_eq!(remove.items.len(), 1);
assert!(matches!(remove.returns, ReturnProjection::Items(ref items) if items.len() == 1));
}
#[test]
fn converts_namespaced_procedure_call_yield_and_predicate() {
let query = parse_query("CALL db.ping() YIELD success AS ok WHERE ok = true RETURN ok")
.expect("parse procedure call");
assert_eq!(query.procedure_calls.len(), 1);
let call = &query.procedure_calls[0];
assert_eq!(call.name, "db.ping");
assert!(call.arguments.is_empty());
assert_eq!(call.yields[0].field, "success");
assert_eq!(call.yields[0].alias.as_deref(), Some("ok"));
assert!(call.predicate.is_some());
assert!(!query.implicit_return);
}
#[test]
fn permits_standalone_procedure_call_without_return() {
let query = parse_query("CALL db.ping()").expect("parse standalone call");
assert!(query.implicit_return);
assert_eq!(query.procedure_calls[0].name, "db.ping");
}
#[test]
fn places_procedure_calls_in_each_with_scope() {
let query = parse_query(
"UNWIND [1] AS n WITH n CALL db.ping() YIELD success \
WITH n, success CALL db.ping() YIELD success AS again \
RETURN n, success, again",
)
.unwrap();
assert!(query.procedure_calls.is_empty());
assert_eq!(query.post_with_procedure_calls[0].name, "db.ping");
assert_eq!(
query.post_with_with_procedure_calls[0].yields[0].binding(),
"again"
);
}
#[test]
fn places_unwind_and_match_after_procedure_calls() {
let query = parse_query(
"CALL db.ping() YIELD success UNWIND [1] AS first MATCH (n) \
WITH first, success CALL db.ping() YIELD success AS second \
UNWIND [2] AS later MATCH (m) RETURN first, later, second",
)
.unwrap();
assert_eq!(query.post_procedure_unwinds[0].variable, "first");
assert_eq!(query.post_procedure_matches.len(), 1);
assert_eq!(query.post_with_procedure_unwinds[0].variable, "later");
assert_eq!(query.post_with_procedure_matches.len(), 1);
assert!(matches!(
parse_query(
"CALL db.ping() YIELD success UNWIND [1] AS n CALL db.ping() RETURN n"
),
Err(crate::Error::UnsupportedQueryFeature(message))
if message.contains("procedure CALL after a post-procedure")
));
}
}