#![allow(dead_code)]
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use regex::Regex;
use crate::api::{Params, QueryResult, Record};
use crate::cypher::ast::{
AngleConversionMode, ComparisonOperator, Direction, Expression, InverseTrigonometricMode,
ListPredicateMode, MatchClause, NodePattern, Operand, OrderDirection, OrderItem, Pattern,
Predicate, PropertyPredicate, RelationshipPattern, ReturnExpression, ReturnItem, RoundingMode,
RowCount, ShortestPathMode, StringOperator, StringSliceMode, TrigonometricMode, TrimMode,
};
use crate::cypher::planner::Plan;
use crate::cypher::procedure::{
resolve as resolve_procedure, ProcedureHandler, ProcedureSignature,
};
use crate::error::{Error, Result};
use crate::graph_model::{Node, NodeId, Relationship, RelationshipId};
use crate::storage_interface::{EmptyEntityLookup, StorageInterface};
use crate::value::{NodeValue, PathValue, RelationshipValue, Value};
#[derive(Clone, Debug, Default)]
#[allow(dead_code)]
pub struct Executor;
#[derive(Clone, Debug, PartialEq)]
enum Binding {
Null,
Node(NodeId),
Relationship(RelationshipId),
Path(PathBinding),
Value(Value),
}
#[derive(Clone, Debug, PartialEq)]
struct PathBinding {
nodes: Vec<NodeId>,
relationships: Vec<RelationshipId>,
}
impl Binding {
fn is_null(&self) -> bool {
matches!(self, Binding::Null)
}
}
type Row = BTreeMap<String, Binding>;
const QUERY_CONTROL_COMPARISON_BATCH: usize = 256;
fn controlled_position<T>(
storage: &dyn StorageInterface,
values: &[T],
mut predicate: impl FnMut(&T) -> bool,
) -> Result<Option<usize>> {
for (chunk_index, chunk) in values.chunks(QUERY_CONTROL_COMPARISON_BATCH).enumerate() {
storage.check_query_control()?;
if let Some(offset) = chunk.iter().position(&mut predicate) {
return Ok(Some(chunk_index * QUERY_CONTROL_COMPARISON_BATCH + offset));
}
}
Ok(None)
}
fn controlled_extend_from_slice<T: Clone>(
storage: &dyn StorageInterface,
output: &mut Vec<T>,
values: &[T],
) -> Result<()> {
for chunk in values.chunks(QUERY_CONTROL_COMPARISON_BATCH) {
storage.check_query_control()?;
output.extend_from_slice(chunk);
}
Ok(())
}
fn controlled_sort_by<T>(
storage: &dyn StorageInterface,
values: &mut [T],
mut compare: impl FnMut(&T, &T) -> Ordering,
) -> Result<()> {
storage.check_query_control()?;
let mut comparisons_until_check = QUERY_CONTROL_COMPARISON_BATCH;
let mut control_error = None;
values.sort_by(|left, right| {
if control_error.is_none() {
comparisons_until_check -= 1;
if comparisons_until_check == 0 {
comparisons_until_check = QUERY_CONTROL_COMPARISON_BATCH;
if let Err(error) = storage.check_query_control() {
control_error = Some(error);
}
}
}
compare(left, right)
});
match control_error {
Some(error) => Err(error),
None => storage.check_query_control(),
}
}
fn path_contains_relationship(
storage: &dyn StorageInterface,
relationships: &[RelationshipId],
relationship_id: RelationshipId,
) -> Result<bool> {
Ok(controlled_position(storage, relationships, |existing| {
*existing == relationship_id
})?
.is_some())
}
pub fn execute(storage: &dyn StorageInterface, plan: Plan, params: &Params) -> Result<QueryResult> {
storage.check_query_control()?;
let match_clauses = plan_match_clauses(&plan);
for clause in &match_clauses {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
}
validate_return_params(&plan.returns, params)?;
if let Some(with) = &plan.with {
validate_predicate_params(with.predicate.as_ref(), params)?;
}
if let Some(with) = &plan.post_with_with {
validate_predicate_params(with.predicate.as_ref(), params)?;
}
if let Some(with) = &plan.post_call_with {
validate_predicate_params(with.predicate.as_ref(), params)?;
}
let mut rows = vec![Row::new()];
for clause in &match_clauses {
rows = apply_match_clause(storage, params, rows, clause)?;
}
for unwind in &plan.unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_unwind_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
for call in &plan.procedure_calls {
rows = apply_procedure_call(storage, params, rows, call)?;
}
for unwind in &plan.post_procedure_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_procedure_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
if let Some(with) = &plan.with {
rows = apply_with_projection(storage, params, rows, with)?;
}
for unwind in &plan.post_with_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_with_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
for call in &plan.post_with_procedure_calls {
rows = apply_procedure_call(storage, params, rows, call)?;
}
for unwind in &plan.post_with_procedure_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_with_procedure_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
for call in &plan.calls {
rows = apply_call_subquery(storage, params, rows, call)?;
}
if let Some(with) = &plan.post_with_with {
rows = apply_with_projection(storage, params, rows, with)?;
}
for unwind in &plan.post_with_with_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_with_with_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
for call in &plan.post_with_with_procedure_calls {
rows = apply_procedure_call(storage, params, rows, call)?;
}
for unwind in &plan.post_with_with_procedure_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_with_with_procedure_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
for call in &plan.post_with_with_calls {
rows = apply_call_subquery(storage, params, rows, call)?;
}
for unwind in &plan.post_call_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_call_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
if let Some(with) = &plan.post_call_with {
rows = apply_with_projection(storage, params, rows, with)?;
}
for unwind in &plan.post_call_with_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_call_with_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
let columns = plan.returns.iter().map(return_column).collect::<Vec<_>>();
if return_items_include_aggregate(&plan.returns) {
let mut projected_rows =
project_aggregate_rows(storage, &rows, &plan.returns, &plan.order_by, params)?;
apply_distinct(storage, &mut projected_rows, plan.distinct)?;
apply_skip(storage, &mut projected_rows, plan.skip.as_ref(), params)?;
apply_limit(storage, &mut projected_rows, plan.limit.as_ref(), params)?;
return Ok(QueryResult {
columns,
rows: projected_rows,
});
}
if !plan.order_by.is_empty() {
apply_return_row_order_by(storage, params, &mut rows, &plan.returns, &plan.order_by)?;
}
let mut rows = rows
.iter()
.map(|row| project_row(storage, row, &plan.returns, params))
.collect::<Result<Vec<_>>>()?;
apply_distinct(storage, &mut rows, plan.distinct)?;
apply_skip(storage, &mut rows, plan.skip.as_ref(), params)?;
apply_limit(storage, &mut rows, plan.limit.as_ref(), params)?;
Ok(QueryResult { columns, rows })
}
fn apply_procedure_call(
storage: &dyn StorageInterface,
params: &Params,
rows: Vec<Row>,
call: &crate::cypher::planner::PlannedProcedureCall,
) -> Result<Vec<Row>> {
let signature = resolve_procedure(&call.name)?;
let mut output_rows = Vec::new();
for row in rows {
storage.check_query_control()?;
let arguments = evaluate_procedure_arguments(storage, params, &row, call, signature)?;
let ProcedureHandler::Read(handler) = signature.handler else {
return Err(Error::UnsupportedProcedureMode {
name: call.name.clone(),
mode: signature.mode.to_string(),
});
};
for procedure_row in handler(storage, &arguments)? {
storage.check_query_control()?;
let procedure_row = procedure_row?;
validate_procedure_row(signature, &procedure_row)?;
let mut merged = row.clone();
for yielded in &call.yields {
let value = procedure_row.get(&yielded.field).cloned().ok_or_else(|| {
Error::Execution(format!(
"procedure `{}` did not produce declared field `{}`",
call.name, yielded.field
))
})?;
merged.insert(yielded.binding.clone(), Binding::Value(value));
}
if call.predicate.as_ref().map_or(Ok(true), |predicate| {
evaluate_predicate(storage, &merged, predicate, params)
})? {
output_rows.push(merged);
}
}
}
Ok(output_rows)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum WriteProcedureStage {
Initial,
PostWith,
PostSecondWith,
}
pub(crate) struct WriteProcedureInvocations {
pub(crate) stage: WriteProcedureStage,
pub(crate) arguments_by_call: Vec<Vec<Vec<Value>>>,
}
pub(crate) fn evaluate_write_procedure_invocations(
storage: &dyn StorageInterface,
params: &Params,
plan: &Plan,
) -> Result<WriteProcedureInvocations> {
storage.check_query_control()?;
let match_clauses = plan_match_clauses(plan);
for clause in &match_clauses {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
}
let mut rows = vec![Row::new()];
for clause in &match_clauses {
rows = apply_match_clause(storage, params, rows, clause)?;
}
for unwind in &plan.unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_unwind_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
if !plan.procedure_calls.is_empty() {
return Ok(WriteProcedureInvocations {
stage: WriteProcedureStage::Initial,
arguments_by_call: evaluate_write_calls(storage, params, &rows, &plan.procedure_calls)?,
});
}
if let Some(with) = &plan.with {
rows = apply_with_projection(storage, params, rows, with)?;
}
for unwind in &plan.post_with_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_with_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
if !plan.post_with_procedure_calls.is_empty() {
return Ok(WriteProcedureInvocations {
stage: WriteProcedureStage::PostWith,
arguments_by_call: evaluate_write_calls(
storage,
params,
&rows,
&plan.post_with_procedure_calls,
)?,
});
}
if let Some(with) = &plan.post_with_with {
rows = apply_with_projection(storage, params, rows, with)?;
}
for unwind in &plan.post_with_with_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
rows = apply_unwind_clause(storage, params, rows, unwind)?;
}
for clause in &plan.post_with_with_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
rows = apply_match_clause(storage, params, rows, clause)?;
}
if !plan.post_with_with_procedure_calls.is_empty() {
return Ok(WriteProcedureInvocations {
stage: WriteProcedureStage::PostSecondWith,
arguments_by_call: evaluate_write_calls(
storage,
params,
&rows,
&plan.post_with_with_procedure_calls,
)?,
});
}
Err(Error::Execution(
"write procedure query has no WRITE call stage".to_owned(),
))
}
fn evaluate_write_calls(
storage: &dyn StorageInterface,
params: &Params,
rows: &[Row],
calls: &[crate::cypher::planner::PlannedProcedureCall],
) -> Result<Vec<Vec<Vec<Value>>>> {
calls
.iter()
.map(|call| {
let signature = resolve_procedure(&call.name)?;
rows.iter()
.map(|row| {
storage.check_query_control()?;
evaluate_procedure_arguments(storage, params, row, call, signature)
})
.collect()
})
.collect()
}
fn evaluate_procedure_arguments(
storage: &dyn StorageInterface,
params: &Params,
row: &Row,
call: &crate::cypher::planner::PlannedProcedureCall,
signature: &ProcedureSignature,
) -> Result<Vec<Value>> {
storage.check_query_control()?;
let mut arguments = call
.arguments
.iter()
.map(|argument| evaluate_row_expression(storage, row, argument, params))
.collect::<Result<Vec<_>>>()?;
for argument in signature.arguments.iter().skip(arguments.len()) {
arguments.push(
argument
.default
.map(|default| default.value())
.ok_or_else(|| Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!("missing argument `{}`", argument.name),
})?,
);
}
for (value, expected) in arguments.iter().zip(signature.arguments) {
if matches!(value, Value::Null) && !expected.nullable {
return Err(Error::InvalidProcedureCall {
name: call.name.clone(),
message: format!("argument `{}` cannot be null", expected.name),
});
}
if !matches!(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),
});
}
}
Ok(arguments)
}
fn validate_procedure_row(
signature: &ProcedureSignature,
row: &BTreeMap<String, Value>,
) -> Result<()> {
for output in signature.outputs {
let value = row.get(output.name).ok_or_else(|| {
Error::Execution(format!(
"procedure `{}` did not produce declared field `{}`",
signature.name, output.name
))
})?;
if matches!(value, Value::Null) && !output.nullable {
return Err(Error::Execution(format!(
"procedure `{}` produced null for non-null field `{}`",
signature.name, output.name
)));
}
if !matches!(value, Value::Null) && !output.value_type.accepts(value) {
return Err(Error::Execution(format!(
"procedure `{}` produced the wrong type for field `{}`",
signature.name, output.name
)));
}
}
if let Some(field) = row
.keys()
.find(|field| !signature.outputs.iter().any(|output| output.name == *field))
{
return Err(Error::Execution(format!(
"procedure `{}` produced undeclared field `{field}`",
signature.name
)));
}
Ok(())
}
fn apply_call_subquery(
storage: &dyn StorageInterface,
params: &Params,
rows: Vec<Row>,
call: &crate::cypher::planner::PlannedCallSubquery,
) -> Result<Vec<Row>> {
let mut output_rows = Vec::new();
for row in rows {
storage.check_query_control()?;
let mut imported = Row::new();
if call.imports.is_empty() {
imported = row.clone();
} else {
for import in &call.imports {
let binding = row.get(import).cloned().ok_or_else(|| {
Error::Validation(format!("CALL import `{import}` is not bound"))
})?;
imported.insert(import.clone(), binding);
}
}
if let Some(predicate) = &call.predicate {
validate_predicate_params(Some(predicate), params)?;
if !evaluate_predicate(storage, &imported, predicate, params)? {
continue;
}
}
let mut call_input_rows = vec![imported];
for unwind in &call.unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
call_input_rows = apply_unwind_clause(storage, params, call_input_rows, unwind)?;
}
for clause in &call.matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
call_input_rows = apply_match_clause(storage, params, call_input_rows, clause)?;
}
for unwind in &call.post_match_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
call_input_rows = apply_unwind_clause(storage, params, call_input_rows, unwind)?;
}
if let Some(with) = &call.with {
call_input_rows = apply_with_projection(storage, params, call_input_rows, with)?;
}
for unwind in &call.post_with_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
call_input_rows = apply_unwind_clause(storage, params, call_input_rows, unwind)?;
}
for clause in &call.post_with_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
call_input_rows = apply_match_clause(storage, params, call_input_rows, clause)?;
}
if let Some(with) = &call.post_with_with {
call_input_rows = apply_with_projection(storage, params, call_input_rows, with)?;
}
for unwind in &call.post_with_with_unwinds {
validate_expression_parameter_refs(&unwind.expression, params)?;
call_input_rows = apply_unwind_clause(storage, params, call_input_rows, unwind)?;
}
for clause in &call.post_with_with_matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
validate_predicate_params(clause.predicate.as_ref(), params)?;
call_input_rows = apply_match_clause(storage, params, call_input_rows, clause)?;
}
let call_rows = apply_with_projection(
storage,
params,
call_input_rows,
&crate::cypher::planner::PlannedWithProjection {
distinct: false,
items: call.items.clone(),
predicate: None,
order_by: Vec::new(),
skip: None,
limit: None,
},
)?;
let mut call_rows = call_rows;
apply_row_order_by(storage, params, &mut call_rows, &call.order_by)?;
apply_row_skip(storage, &mut call_rows, call.skip.as_ref(), params)?;
apply_row_limit(storage, &mut call_rows, call.limit.as_ref(), params)?;
for call_row in call_rows {
storage.check_query_control()?;
let mut output_row = row.clone();
for (key, value) in call_row {
output_row.insert(key, value);
}
output_rows.push(output_row);
}
}
Ok(output_rows)
}
fn apply_unwind_clause(
storage: &dyn StorageInterface,
params: &Params,
rows: Vec<Row>,
unwind: &crate::cypher::ast::UnwindClause,
) -> Result<Vec<Row>> {
let mut output_rows = Vec::new();
for row in rows {
storage.check_query_control()?;
match evaluate_row_expression(storage, &row, &unwind.expression, params)? {
Value::List(values) => {
for value in values {
storage.check_query_control()?;
let mut output_row = row.clone();
output_row.insert(unwind.variable.clone(), Binding::Value(value));
output_rows.push(output_row);
}
}
Value::Null => {}
_ => {
return Err(Error::Validation(
"UNWIND expression must evaluate to a list".to_string(),
));
}
}
}
Ok(output_rows)
}
fn apply_with_projection(
storage: &dyn StorageInterface,
params: &Params,
rows: Vec<Row>,
with: &crate::cypher::planner::PlannedWithProjection,
) -> Result<Vec<Row>> {
if return_items_include_aggregate(&with.items) {
return apply_with_aggregate_projection(storage, params, rows, with);
}
let mut projected_rows = rows
.into_iter()
.map(|row| project_with_row(storage, params, row, &with.items))
.collect::<Result<Vec<_>>>()?;
apply_row_distinct(storage, &mut projected_rows, with.distinct)?;
filter_with_predicate(
storage,
params,
&mut projected_rows,
with.predicate.as_ref(),
)?;
apply_row_order_by(storage, params, &mut projected_rows, &with.order_by)?;
apply_row_skip(storage, &mut projected_rows, with.skip.as_ref(), params)?;
apply_row_limit(storage, &mut projected_rows, with.limit.as_ref(), params)?;
Ok(projected_rows)
}
fn apply_with_aggregate_projection(
storage: &dyn StorageInterface,
params: &Params,
rows: Vec<Row>,
with: &crate::cypher::planner::PlannedWithProjection,
) -> Result<Vec<Row>> {
let group_items = with
.items
.iter()
.filter(|item| !return_expression_is_aggregate(&item.expression))
.collect::<Vec<_>>();
let groups = aggregate_groups(storage, &rows, &group_items, params)?;
let mut projected_rows = groups
.iter()
.map(|group| project_with_aggregate_group(storage, params, group, &with.items))
.collect::<Result<Vec<_>>>()?;
apply_row_distinct(storage, &mut projected_rows, with.distinct)?;
filter_with_predicate(
storage,
params,
&mut projected_rows,
with.predicate.as_ref(),
)?;
apply_row_order_by(storage, params, &mut projected_rows, &with.order_by)?;
apply_row_skip(storage, &mut projected_rows, with.skip.as_ref(), params)?;
apply_row_limit(storage, &mut projected_rows, with.limit.as_ref(), params)?;
Ok(projected_rows)
}
fn filter_with_predicate(
storage: &dyn StorageInterface,
params: &Params,
rows: &mut Vec<Row>,
predicate: Option<&Predicate>,
) -> Result<()> {
let Some(predicate) = predicate else {
return Ok(());
};
let mut filtered_rows = Vec::new();
for row in rows.drain(..) {
if evaluate_predicate(storage, &row, predicate, params)? {
filtered_rows.push(row);
}
}
*rows = filtered_rows;
Ok(())
}
fn apply_row_distinct(
storage: &dyn StorageInterface,
rows: &mut Vec<Row>,
distinct: bool,
) -> Result<()> {
if !distinct {
return Ok(());
}
let mut seen = Vec::<Row>::new();
let mut distinct_rows = Vec::with_capacity(rows.len());
for row in rows.drain(..) {
storage.check_query_control()?;
if controlled_position(storage, &seen, |seen_row| seen_row == &row)?.is_none() {
seen.push(row.clone());
distinct_rows.push(row);
}
}
*rows = distinct_rows;
Ok(())
}
fn apply_row_limit(
storage: &dyn StorageInterface,
rows: &mut Vec<Row>,
limit: Option<&RowCount>,
params: &Params,
) -> Result<()> {
let Some(limit) = limit else {
return Ok(());
};
let limit = resolve_row_count(storage, "WITH LIMIT", limit, params)?;
rows.truncate(limit);
Ok(())
}
fn apply_row_order_by(
storage: &dyn StorageInterface,
params: &Params,
rows: &mut Vec<Row>,
order_by: &[OrderItem],
) -> Result<()> {
if order_by.is_empty() {
return Ok(());
}
storage.check_query_control()?;
let mut keyed_rows = rows
.drain(..)
.map(|row| {
storage.check_query_control()?;
let keys = order_by
.iter()
.map(|order_item| {
project_item(storage, &row, &order_item.item, params)
.map(|value| (value, order_item.direction))
})
.collect::<Result<Vec<_>>>()?;
Ok((row, keys))
})
.collect::<Result<Vec<_>>>()?;
controlled_sort_by(
storage,
&mut keyed_rows,
|(_, left_keys), (_, right_keys)| compare_order_keys(left_keys, right_keys),
)?;
rows.extend(keyed_rows.into_iter().map(|(row, _)| row));
Ok(())
}
fn apply_return_row_order_by(
storage: &dyn StorageInterface,
params: &Params,
rows: &mut Vec<Row>,
returns: &[ReturnItem],
order_by: &[OrderItem],
) -> Result<()> {
let order_by = order_by
.iter()
.map(|order_item| resolve_source_row_order_item(order_item, returns))
.collect::<Vec<_>>();
apply_row_order_by(storage, params, rows, &order_by)
}
fn resolve_source_row_order_item(order_item: &OrderItem, returns: &[ReturnItem]) -> OrderItem {
let ReturnExpression::Variable(alias) = &order_item.item.expression else {
return order_item.clone();
};
let Some(return_item) = returns
.iter()
.find(|return_item| return_item.alias.as_deref() == Some(alias.as_str()))
else {
return order_item.clone();
};
OrderItem {
item: ReturnItem {
expression: return_item.expression.clone(),
alias: None,
},
direction: order_item.direction,
}
}
fn compare_order_keys(
left: &[(Value, OrderDirection)],
right: &[(Value, OrderDirection)],
) -> Ordering {
for ((left_value, direction), (right_value, _)) in left.iter().zip(right.iter()) {
let ordering = compare_sort_values(left_value, right_value);
let ordering = match direction {
OrderDirection::Ascending => ordering,
OrderDirection::Descending => ordering.reverse(),
};
if ordering != Ordering::Equal {
return ordering;
}
}
Ordering::Equal
}
fn apply_row_skip(
storage: &dyn StorageInterface,
rows: &mut Vec<Row>,
skip: Option<&RowCount>,
params: &Params,
) -> Result<()> {
let Some(skip) = skip else {
return Ok(());
};
let skip = resolve_row_count(storage, "WITH SKIP", skip, params)?;
if skip >= rows.len() {
rows.clear();
} else {
rows.drain(0..skip);
}
Ok(())
}
fn project_with_aggregate_group(
storage: &dyn StorageInterface,
params: &Params,
group: &AggregateGroup,
items: &[ReturnItem],
) -> Result<Row> {
let first_row = group.rows.first();
let mut projected = Row::new();
for item in items {
let output_variable = return_column(item);
let binding = if return_expression_is_aggregate(&item.expression) {
Binding::Value(aggregate_value(
storage,
&group.rows,
&item.expression,
params,
)?)
} else {
let row = first_row.ok_or_else(|| {
Error::Execution("aggregate group is missing source rows".to_string())
})?;
match &item.expression {
ReturnExpression::Variable(variable) => row.get(variable).cloned().ok_or_else(|| {
Error::Validation(format!("WITH variable `{variable}` is not bound"))
})?,
ReturnExpression::Property { .. }
| ReturnExpression::Scalar(_)
| ReturnExpression::Labels(_)
| ReturnExpression::Type(_)
| ReturnExpression::Properties(_)
| ReturnExpression::Keys(_)
| ReturnExpression::ElementId(_)
| ReturnExpression::Id(_)
| ReturnExpression::StartNode(_)
| ReturnExpression::EndNode(_)
| ReturnExpression::Nodes(_)
| ReturnExpression::Relationships(_)
| ReturnExpression::Length(_) => Binding::Value(project_item(storage, row, item, params)?),
_ => {
return Err(Error::UnsupportedQueryFeature(
"WITH aggregate grouping currently supports variables, properties, and scalar literals"
.to_string(),
))
}
}
};
projected.insert(output_variable, binding);
}
Ok(projected)
}
fn project_with_row(
storage: &dyn StorageInterface,
params: &Params,
row: Row,
items: &[ReturnItem],
) -> Result<Row> {
storage.check_query_control()?;
let mut projected = Row::new();
for item in items {
let (output_variable, binding) = match &item.expression {
ReturnExpression::Variable(variable) => {
let binding = row.get(variable).cloned().ok_or_else(|| {
Error::Validation(format!("WITH variable `{variable}` is not bound"))
})?;
(item.alias.as_ref().unwrap_or(variable).clone(), binding)
}
ReturnExpression::Property { variable, key } => (
item.alias.clone().unwrap_or_else(|| return_column(item)),
Binding::Value(property_value(storage, &row, variable, key)?),
),
ReturnExpression::PropertyWildcard(_) => (
item.alias.clone().unwrap_or_else(|| return_column(item)),
Binding::Value(project_item(storage, &row, item, params)?),
),
ReturnExpression::Scalar(expression) => (
item.alias.clone().unwrap_or_else(|| return_column(item)),
Binding::Value(evaluate_row_expression(storage, &row, expression, params)?),
),
ReturnExpression::Labels(_)
| ReturnExpression::Type(_)
| ReturnExpression::Properties(_)
| ReturnExpression::Keys(_)
| ReturnExpression::ElementId(_)
| ReturnExpression::Id(_)
| ReturnExpression::StartNode(_)
| ReturnExpression::EndNode(_)
| ReturnExpression::Nodes(_)
| ReturnExpression::Relationships(_)
| ReturnExpression::Length(_) => (
item.alias.clone().unwrap_or_else(|| return_column(item)),
Binding::Value(project_item(storage, &row, item, params)?),
),
_ => {
return Err(Error::UnsupportedQueryFeature(
"WITH currently supports variables, properties, scalar literals, and *"
.to_string(),
))
}
};
projected.insert(output_variable, binding);
}
Ok(projected)
}
fn plan_match_clauses(plan: &Plan) -> Vec<MatchClause> {
let mut clauses = if plan.has_initial_match {
vec![MatchClause {
optional_match: plan.optional_match,
pattern: plan.pattern.clone(),
patterns: plan.patterns.clone(),
predicate: plan.predicate.clone(),
}]
} else {
Vec::new()
};
clauses.extend(plan.extra_matches.clone());
clauses
}
fn apply_match_clause(
storage: &dyn StorageInterface,
params: &Params,
input_rows: Vec<Row>,
clause: &MatchClause,
) -> Result<Vec<Row>> {
let mut output_rows = Vec::new();
let null_variables = clause
.patterns
.iter()
.map(pattern_bound_variables)
.collect::<Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect::<Vec<_>>();
for input_row in input_rows {
storage.check_query_control()?;
let mut matched_rows = vec![input_row.clone()];
for pattern in &clause.patterns {
let mut next_rows = Vec::new();
for row in &matched_rows {
storage.check_query_control()?;
next_rows.extend(match_pattern(storage, params, row, pattern)?);
}
matched_rows = next_rows;
}
if let Some(predicate) = &clause.predicate {
matched_rows = matched_rows
.into_iter()
.filter_map(
|row| match evaluate_predicate(storage, &row, predicate, params) {
Ok(true) => Some(Ok(row)),
Ok(false) => None,
Err(error) => Some(Err(error)),
},
)
.collect::<Result<Vec<_>>>()?;
}
if matched_rows.is_empty() && clause.optional_match {
let mut null_row = input_row;
for variable in &null_variables {
null_row.entry(variable.clone()).or_insert(Binding::Null);
}
output_rows.push(null_row);
} else {
output_rows.extend(matched_rows);
}
}
Ok(output_rows)
}
fn match_pattern(
storage: &dyn StorageInterface,
params: &Params,
input_row: &Row,
pattern: &Pattern,
) -> Result<Vec<Row>> {
if let Some(mode) = pattern.shortest_path {
return match_shortest_path_pattern(storage, params, input_row, pattern, mode);
}
let (pattern, internal_variables) = bind_anonymous_pattern_nodes(pattern);
let mut rows = Vec::new();
for node_id in start_node_ids_for_row(storage, input_row, &pattern.start)? {
storage.check_query_control()?;
let node = storage_node(storage, node_id)?;
if node_matches(storage, input_row, node, &pattern.start, params)? {
let mut row = input_row.clone();
if bind_node(&mut row, pattern.start.variable.as_ref(), node.id)? {
rows.push(row);
}
}
}
let single_variable_length_path_variable = match &pattern.variable {
Some(variable)
if pattern.chains.len() == 1 && pattern.chains[0].relationship.variable_length =>
{
Some(variable.as_str())
}
_ => None,
};
for (chain_index, chain) in pattern.chains.iter().enumerate() {
let mut next_rows = Vec::new();
let variable_length_path_segment_variable = (pattern.variable.is_some()
&& chain.relationship.variable_length)
.then(|| variable_length_path_segment_variable(chain_index));
for row in &rows {
storage.check_query_control()?;
let left_variable = chain.left_variable.as_ref().ok_or_else(|| {
Error::Execution("pattern chain is missing a left variable".to_string())
})?;
let source_id = bound_node(row, left_variable)?;
if chain.relationship.variable_length {
expand_variable_length_chain(
storage,
params,
chain,
row,
source_id,
single_variable_length_path_variable
.or(variable_length_path_segment_variable.as_deref()),
&mut next_rows,
)?;
} else {
expand_fixed_length_chain(storage, params, chain, row, source_id, &mut next_rows)?;
}
}
rows = next_rows;
}
if pattern.variable.is_some() && single_variable_length_path_variable.is_none() {
rows = rows
.into_iter()
.map(|mut row| {
bind_path(storage, &mut row, &pattern)?;
Ok(row)
})
.collect::<Result<Vec<_>>>()?;
}
for row in &mut rows {
storage.check_query_control()?;
for variable in &internal_variables {
row.remove(variable);
}
}
Ok(rows)
}
fn evaluate_pattern_comprehension_value(
storage: &dyn StorageInterface,
row: &Row,
pattern: &Pattern,
predicate: Option<&Predicate>,
projection: &Expression,
params: &Params,
) -> Result<Value> {
let mut rows = match_pattern(storage, params, row, pattern)?;
if let Some(predicate) = predicate {
rows = rows
.into_iter()
.filter_map(
|row| match evaluate_predicate(storage, &row, predicate, params) {
Ok(true) => Some(Ok(row)),
Ok(false) => None,
Err(error) => Some(Err(error)),
},
)
.collect::<Result<Vec<_>>>()?;
}
rows.iter()
.map(|row| evaluate_row_expression(storage, row, projection, params))
.collect::<Result<Vec<_>>>()
.map(Value::List)
}
#[derive(Clone, Debug)]
struct ShortestPathState {
node: NodeId,
nodes: Vec<NodeId>,
relationships: Vec<RelationshipId>,
}
fn match_shortest_path_pattern(
storage: &dyn StorageInterface,
params: &Params,
input_row: &Row,
pattern: &Pattern,
mode: ShortestPathMode,
) -> Result<Vec<Row>> {
if pattern.chains.len() != 1 {
return match_multi_segment_shortest_path_pattern(
storage, params, input_row, pattern, mode,
);
}
let chain = &pattern.chains[0];
let mut output_rows = Vec::new();
let mut best_length = None::<usize>;
for start_id in start_node_ids_for_row(storage, input_row, &pattern.start)? {
storage.check_query_control()?;
let start = storage_node(storage, start_id)?;
if !node_matches(storage, input_row, start, &pattern.start, params)? {
continue;
}
let paths = if chain.relationship.variable_length {
shortest_paths_from(storage, params, chain, start_id, best_length)?
} else {
fixed_length_shortest_paths_from(storage, params, chain, start_id)?
};
for path in paths {
storage.check_query_control()?;
let length = path.relationships.len();
match best_length {
Some(best) if length > best => continue,
Some(best) if length < best => {
output_rows.clear();
best_length = Some(length);
}
None => best_length = Some(length),
_ => {}
}
let mut row = input_row.clone();
if !bind_node(&mut row, pattern.start.variable.as_ref(), start_id)? {
continue;
}
if let Some(end_id) = path.nodes.last() {
if !bind_node(&mut row, chain.node.variable.as_ref(), *end_id)? {
continue;
}
}
if !chain.relationship.variable_length {
if let Some(relationship_id) = path.relationships.first() {
if !bind_relationship(
&mut row,
chain.relationship.variable.as_ref(),
*relationship_id,
)? {
continue;
}
}
}
if let Some(path_variable) = pattern.variable.as_ref() {
if !bind(
&mut row,
path_variable,
Binding::Path(PathBinding {
nodes: path.nodes,
relationships: path.relationships,
}),
)? {
continue;
}
}
output_rows.push(row);
if mode == ShortestPathMode::Single {
return Ok(output_rows);
}
}
}
Ok(output_rows)
}
fn bind_anonymous_pattern_nodes(pattern: &Pattern) -> (Pattern, Vec<String>) {
let mut pattern = pattern.clone();
let mut internal_variables = Vec::new();
let mut left_variable = pattern.start.variable.clone();
if left_variable.is_none() {
let variable = "__littlegraph_match_node_0".to_owned();
pattern.start.variable = Some(variable.clone());
left_variable = Some(variable.clone());
internal_variables.push(variable);
}
for (index, chain) in pattern.chains.iter_mut().enumerate() {
chain.left_variable = left_variable.clone();
if chain.node.variable.is_none() {
let variable = format!("__littlegraph_match_node_{}", index + 1);
chain.node.variable = Some(variable.clone());
internal_variables.push(variable.clone());
left_variable = Some(variable);
} else {
left_variable = chain.node.variable.clone();
}
}
(pattern, internal_variables)
}
fn match_multi_segment_shortest_path_pattern(
storage: &dyn StorageInterface,
params: &Params,
input_row: &Row,
pattern: &Pattern,
mode: ShortestPathMode,
) -> Result<Vec<Row>> {
let path_variable = pattern
.variable
.clone()
.unwrap_or_else(shortest_path_internal_variable);
let mut regular_pattern = path_bindable_pattern(pattern, &path_variable);
regular_pattern.shortest_path = None;
let rows = match_pattern(storage, params, input_row, ®ular_pattern)?;
let mut output_rows = Vec::new();
let mut best_length = None::<usize>;
for mut row in rows {
storage.check_query_control()?;
let length = path_length(&row, &path_variable)?;
match best_length {
Some(best) if length > best => continue,
Some(best) if length < best => {
output_rows.clear();
best_length = Some(length);
}
None => best_length = Some(length),
_ => {}
}
if pattern.variable.is_none() {
row.remove(&path_variable);
}
output_rows.push(row);
}
if mode == ShortestPathMode::Single {
output_rows.truncate(1);
}
Ok(output_rows)
}
fn path_bindable_pattern(pattern: &Pattern, path_variable: &str) -> Pattern {
let mut pattern = pattern.clone();
pattern.variable = Some(path_variable.to_string());
if pattern.start.variable.is_none() {
pattern.start.variable = Some(shortest_path_internal_node_variable(0));
}
let mut left_variable = pattern.start.variable.clone();
let chain_count = pattern.chains.len();
for (index, chain) in pattern.chains.iter_mut().enumerate() {
chain.left_variable = left_variable.clone();
if chain.node.variable.is_none() {
chain.node.variable = Some(shortest_path_internal_node_variable(index + 1));
}
if chain.relationship.variable.is_none() && !chain.relationship.variable_length {
chain.relationship.variable = Some(shortest_path_internal_relationship_variable(index));
}
if index + 1 < chain_count {
left_variable = chain.node.variable.clone();
}
}
pattern
}
fn shortest_path_internal_variable() -> String {
"__littlegraph_shortest_path".to_string()
}
fn shortest_path_internal_node_variable(index: usize) -> String {
format!("__littlegraph_shortest_path_node_{index}")
}
fn shortest_path_internal_relationship_variable(index: usize) -> String {
format!("__littlegraph_shortest_path_rel_{index}")
}
fn fixed_length_shortest_paths_from(
storage: &dyn StorageInterface,
params: &Params,
chain: &crate::cypher::ast::PatternChain,
start_id: NodeId,
) -> Result<Vec<ShortestPathState>> {
let mut results = Vec::new();
for relationship_id in
relationship_ids_for_direction(storage, start_id, chain.relationship.direction)
{
let relationship = storage_relationship(storage, relationship_id)?;
if !relationship_matches(
storage,
&Row::new(),
relationship,
&chain.relationship,
params,
)? {
continue;
}
let Some(endpoint_id) =
endpoint_for_direction(relationship, start_id, chain.relationship.direction)
else {
return Err(Error::Execution(format!(
"relationship {} is not connected to node {}",
relationship.id, start_id
)));
};
if !node_matches(
storage,
&Row::new(),
storage_node(storage, endpoint_id)?,
&chain.node,
params,
)? {
continue;
}
results.push(ShortestPathState {
node: endpoint_id,
nodes: vec![start_id, endpoint_id],
relationships: vec![relationship_id],
});
}
Ok(results)
}
fn shortest_paths_from(
storage: &dyn StorageInterface,
params: &Params,
chain: &crate::cypher::ast::PatternChain,
start_id: NodeId,
known_best: Option<usize>,
) -> Result<Vec<ShortestPathState>> {
let mut queue = VecDeque::from([ShortestPathState {
node: start_id,
nodes: vec![start_id],
relationships: Vec::new(),
}]);
let mut results = Vec::new();
let mut best_length = known_best;
while let Some(state) = queue.pop_front() {
storage.check_query_control()?;
let depth = state.relationships.len();
if best_length.is_some_and(|best| depth > best) {
continue;
}
if chain
.relationship
.max_hops
.is_some_and(|max_hops| depth >= max_hops)
{
continue;
}
for relationship_id in
relationship_ids_for_direction(storage, state.node, chain.relationship.direction)
{
if path_contains_relationship(storage, &state.relationships, relationship_id)? {
continue;
}
let relationship = storage_relationship(storage, relationship_id)?;
if !relationship_matches(
storage,
&Row::new(),
relationship,
&chain.relationship,
params,
)? {
continue;
}
let Some(endpoint_id) =
endpoint_for_direction(relationship, state.node, chain.relationship.direction)
else {
return Err(Error::Execution(format!(
"relationship {} is not connected to node {}",
relationship.id, state.node
)));
};
let mut next = state.clone();
next.node = endpoint_id;
next.nodes.push(endpoint_id);
next.relationships.push(relationship_id);
let next_depth = next.relationships.len();
if best_length.is_some_and(|best| next_depth > best) {
continue;
}
if next_depth >= chain.relationship.min_hops
&& node_matches(
storage,
&Row::new(),
storage_node(storage, endpoint_id)?,
&chain.node,
params,
)?
{
match best_length {
Some(best) if next_depth < best => {
results.clear();
best_length = Some(next_depth);
}
None => best_length = Some(next_depth),
_ => {}
}
if best_length == Some(next_depth) {
results.push(next);
}
continue;
}
queue.push_back(next);
}
}
Ok(results)
}
fn path_length(row: &Row, variable: &str) -> Result<usize> {
match row.get(variable) {
Some(Binding::Path(path)) => Ok(path.relationships.len()),
Some(Binding::Null) => Ok(0),
Some(_) => Err(Error::Validation(format!(
"variable `{variable}` is not bound to a path"
))),
None => Err(Error::Validation(format!(
"variable `{variable}` is not bound"
))),
}
}
fn validate_params(pattern: &Pattern, params: &Params) -> Result<()> {
validate_property_params(&pattern.start.properties, params)?;
for chain in &pattern.chains {
validate_property_params(&chain.relationship.properties, params)?;
validate_property_params(&chain.node.properties, params)?;
}
Ok(())
}
fn validate_property_params(predicates: &[PropertyPredicate], params: &Params) -> Result<()> {
for predicate in predicates {
validate_expression_parameter_refs(&predicate.expression, params)?;
}
Ok(())
}
fn validate_predicate_params(predicate: Option<&Predicate>, params: &Params) -> Result<()> {
if let Some(predicate) = predicate {
validate_predicate_parameter_refs(predicate, params)?;
}
Ok(())
}
fn validate_predicate_parameter_refs(predicate: &Predicate, params: &Params) -> Result<()> {
match predicate {
Predicate::Comparison { left, right, .. } => {
validate_expression_parameter_refs(left, params)?;
validate_expression_parameter_refs(right, params)
}
Predicate::In { item, list } => {
validate_expression_parameter_refs(item, params)?;
validate_in_list_parameter_ref(list, params)
}
Predicate::StringMatch { left, right, .. } => {
validate_expression_parameter_refs(left, params)?;
validate_expression_parameter_refs(right, params)
}
Predicate::And(left, right) | Predicate::Or(left, right) | Predicate::Xor(left, right) => {
validate_predicate_parameter_refs(left, params)?;
validate_predicate_parameter_refs(right, params)
}
Predicate::Not(inner) => validate_predicate_parameter_refs(inner, params),
Predicate::Pattern(_) => Ok(()),
Predicate::IsNull(expression) | Predicate::IsNotNull(expression) => {
validate_expression_parameter_refs(expression, params)
}
Predicate::Exists(operand) => validate_operand_parameter_refs(operand, params),
Predicate::ExistsSubquery(matches) => {
for clause in matches {
for pattern in &clause.patterns {
validate_params(pattern, params)?;
}
if let Some(predicate) = &clause.predicate {
validate_predicate_parameter_refs(predicate, params)?;
}
}
Ok(())
}
Predicate::Boolean(expression) => validate_expression_parameter_refs(expression, params),
}
}
fn validate_return_params(returns: &[ReturnItem], params: &Params) -> Result<()> {
for item in returns {
if let ReturnExpression::Scalar(expression) = &item.expression {
validate_expression_parameter_refs(expression, params)?;
}
}
Ok(())
}
fn validate_expression_parameter_refs(expression: &Expression, params: &Params) -> Result<()> {
match expression {
Expression::Literal(_) => Ok(()),
Expression::Parameter(name) => {
params
.get(name)
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`")))?;
Ok(())
}
Expression::Operand(operand) => validate_operand_parameter_refs(operand, params),
Expression::Add(left, right)
| Expression::Subtract(left, right)
| Expression::Multiply(left, right)
| Expression::Divide(left, right)
| Expression::Modulo(left, right) => {
validate_expression_parameter_refs(left, params)?;
validate_expression_parameter_refs(right, params)
}
Expression::ToLower(expression)
| Expression::ToUpper(expression)
| Expression::ToString(expression)
| Expression::ToInteger(expression)
| Expression::ToFloat(expression)
| Expression::ToBoolean(expression)
| Expression::ToStringOrNull(expression)
| Expression::ToIntegerOrNull(expression)
| Expression::ToFloatOrNull(expression)
| Expression::ToBooleanOrNull(expression)
| Expression::IsEmpty(expression)
| Expression::Head(expression)
| Expression::Last(expression)
| Expression::Tail(expression)
| Expression::Size(expression) => validate_expression_parameter_refs(expression, params),
Expression::Range { start, end, step } => {
validate_expression_parameter_refs(start, params)?;
validate_expression_parameter_refs(end, params)?;
if let Some(step) = step {
validate_expression_parameter_refs(step, params)?;
}
Ok(())
}
Expression::ListIndex { value, index } => {
validate_expression_parameter_refs(value, params)?;
validate_expression_parameter_refs(index, params)
}
Expression::ListSlice { value, start, end } => {
validate_expression_parameter_refs(value, params)?;
if let Some(start) = start {
validate_expression_parameter_refs(start, params)?;
}
if let Some(end) = end {
validate_expression_parameter_refs(end, params)?;
}
Ok(())
}
Expression::Substring {
value,
start,
length,
} => {
validate_expression_parameter_refs(value, params)?;
validate_expression_parameter_refs(start, params)?;
if let Some(length) = length {
validate_expression_parameter_refs(length, params)?;
}
Ok(())
}
Expression::Replace {
value,
search,
replacement,
} => {
validate_expression_parameter_refs(value, params)?;
validate_expression_parameter_refs(search, params)?;
validate_expression_parameter_refs(replacement, params)
}
Expression::Trim { expression, .. } => {
validate_expression_parameter_refs(expression, params)
}
Expression::Split { value, delimiter } => {
validate_expression_parameter_refs(value, params)?;
validate_expression_parameter_refs(delimiter, params)
}
Expression::StringSlice { value, length, .. } => {
validate_expression_parameter_refs(value, params)?;
validate_expression_parameter_refs(length, params)
}
Expression::Reverse(expression) => validate_expression_parameter_refs(expression, params),
Expression::Abs(expression) => validate_expression_parameter_refs(expression, params),
Expression::Rounding { expression, .. } => {
validate_expression_parameter_refs(expression, params)
}
Expression::Sign(expression) => validate_expression_parameter_refs(expression, params),
Expression::Sqrt(expression) => validate_expression_parameter_refs(expression, params),
Expression::Round(expression) => validate_expression_parameter_refs(expression, params),
Expression::Log(expression) => validate_expression_parameter_refs(expression, params),
Expression::Log10(expression) => validate_expression_parameter_refs(expression, params),
Expression::Exp(expression) => validate_expression_parameter_refs(expression, params),
Expression::AngleConversion { expression, .. } => {
validate_expression_parameter_refs(expression, params)
}
Expression::Trigonometric { expression, .. } => {
validate_expression_parameter_refs(expression, params)
}
Expression::InverseTrigonometric { expression, .. } => {
validate_expression_parameter_refs(expression, params)
}
Expression::Atan2 { y, x } => {
validate_expression_parameter_refs(y, params)?;
validate_expression_parameter_refs(x, params)
}
Expression::Haversin(expression) => validate_expression_parameter_refs(expression, params),
Expression::Pi | Expression::E => Ok(()),
Expression::List(items) => {
for item in items {
validate_expression_parameter_refs(item, params)?;
}
Ok(())
}
Expression::Map(entries) => {
for value in entries.values() {
validate_expression_parameter_refs(value, params)?;
}
Ok(())
}
Expression::MapProjection { items, .. } => {
for item in items {
if let crate::cypher::ast::MapProjectionItem::Expression { expression, .. } = item {
validate_expression_parameter_refs(expression, params)?;
}
}
Ok(())
}
Expression::Coalesce(items) => {
for item in items {
validate_expression_parameter_refs(item, params)?;
}
Ok(())
}
Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
validate_predicate_parameter_refs(&alternative.predicate, params)?;
validate_expression_parameter_refs(&alternative.expression, params)?;
}
validate_expression_parameter_refs(else_expression, params)
}
Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
validate_expression_parameter_refs(operand, params)?;
for alternative in alternatives {
validate_expression_parameter_refs(&alternative.value, params)?;
validate_expression_parameter_refs(&alternative.expression, params)?;
}
validate_expression_parameter_refs(else_expression, params)
}
Expression::Predicate(predicate) => validate_predicate_parameter_refs(predicate, params),
Expression::ListPredicate {
list, predicate, ..
} => {
validate_expression_parameter_refs(list, params)?;
validate_predicate_parameter_refs(predicate, params)
}
Expression::ListComprehension {
list,
predicate,
projection,
..
} => {
validate_expression_parameter_refs(list, params)?;
if let Some(predicate) = predicate {
validate_predicate_parameter_refs(predicate, params)?;
}
validate_expression_parameter_refs(projection, params)
}
Expression::PatternComprehension {
predicate,
projection,
..
} => {
if let Some(predicate) = predicate {
validate_predicate_parameter_refs(predicate, params)?;
}
validate_expression_parameter_refs(projection, params)
}
Expression::Reduce {
initial,
list,
expression,
..
} => {
validate_expression_parameter_refs(initial, params)?;
validate_expression_parameter_refs(list, params)?;
validate_expression_parameter_refs(expression, params)
}
}
}
fn validate_operand_parameter_refs(operand: &Operand, params: &Params) -> Result<()> {
match operand {
Operand::Parameter(name) => {
params
.get(name)
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`")))?;
}
Operand::DynamicProperty { key, .. } => validate_expression_parameter_refs(key, params)?,
Operand::Literal(_) | Operand::Property { .. } | Operand::Variable(_) => {}
}
Ok(())
}
fn validate_in_list_parameter_ref(list: &Expression, params: &Params) -> Result<()> {
let Expression::Parameter(name) = list else {
return validate_expression_parameter_refs(list, params);
};
match params
.get(name)
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`")))?
{
Value::List(_) => Ok(()),
_ => Err(Error::Validation(format!(
"IN parameter `{name}` must be a list"
))),
}
}
fn start_node_ids(storage: &dyn StorageInterface, pattern: &NodePattern) -> Vec<NodeId> {
pattern.labels.first().map_or_else(
|| storage.node_ids(),
|label| storage.nodes_with_label(label).to_vec(),
)
}
fn start_node_ids_for_row(
storage: &dyn StorageInterface,
row: &Row,
pattern: &NodePattern,
) -> Result<Vec<NodeId>> {
let Some(variable) = &pattern.variable else {
return Ok(start_node_ids(storage, pattern));
};
match row.get(variable) {
Some(Binding::Node(node_id)) => Ok(vec![*node_id]),
Some(Binding::Null) => Ok(Vec::new()),
Some(Binding::Relationship(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a relationship, not a node"
))),
Some(Binding::Path(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a path, not a node"
))),
Some(Binding::Value(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a value, not a node"
))),
None => Ok(start_node_ids(storage, pattern)),
}
}
fn relationship_ids_for_direction(
storage: &dyn StorageInterface,
source_id: NodeId,
direction: Direction,
) -> Vec<RelationshipId> {
match direction {
Direction::Outgoing => storage.outgoing_relationships(source_id).to_vec(),
Direction::Incoming => storage.incoming_relationships(source_id).to_vec(),
Direction::Undirected => {
let mut seen = BTreeSet::new();
let mut ids = Vec::new();
for id in storage
.outgoing_relationships(source_id)
.iter()
.chain(storage.incoming_relationships(source_id))
{
if seen.insert(*id) {
ids.push(*id);
}
}
ids
}
}
}
fn expand_fixed_length_chain(
storage: &dyn StorageInterface,
params: &Params,
chain: &crate::cypher::ast::PatternChain,
row: &Row,
source_id: NodeId,
next_rows: &mut Vec<Row>,
) -> Result<()> {
for relationship_id in
relationship_ids_for_direction(storage, source_id, chain.relationship.direction)
{
let relationship = storage_relationship(storage, relationship_id)?;
let Some(endpoint_id) =
endpoint_for_direction(relationship, source_id, chain.relationship.direction)
else {
return Err(Error::Execution(format!(
"relationship {} is not connected to node {}",
relationship.id, source_id
)));
};
let endpoint = storage_node(storage, endpoint_id)?;
if !relationship_matches(storage, row, relationship, &chain.relationship, params)? {
continue;
}
if !node_matches(storage, row, endpoint, &chain.node, params)? {
continue;
}
let mut next_row = row.clone();
if !bind_relationship(
&mut next_row,
chain.relationship.variable.as_ref(),
relationship.id,
)? {
continue;
}
if !bind_node(&mut next_row, chain.node.variable.as_ref(), endpoint.id)? {
continue;
}
next_rows.push(next_row);
}
Ok(())
}
fn expand_variable_length_chain(
storage: &dyn StorageInterface,
params: &Params,
chain: &crate::cypher::ast::PatternChain,
row: &Row,
source_id: NodeId,
path_variable: Option<&str>,
next_rows: &mut Vec<Row>,
) -> Result<()> {
let mut nodes = vec![source_id];
let mut relationships = Vec::new();
expand_variable_length_from(
storage,
params,
chain,
row,
source_id,
&mut nodes,
&mut relationships,
path_variable,
next_rows,
)
}
#[allow(clippy::too_many_arguments)]
fn expand_variable_length_from(
storage: &dyn StorageInterface,
params: &Params,
chain: &crate::cypher::ast::PatternChain,
row: &Row,
source_id: NodeId,
nodes: &mut Vec<NodeId>,
relationships: &mut Vec<RelationshipId>,
path_variable: Option<&str>,
next_rows: &mut Vec<Row>,
) -> Result<()> {
let depth = relationships.len();
if depth >= chain.relationship.min_hops {
let endpoint = storage_node(storage, source_id)?;
if node_matches(storage, row, endpoint, &chain.node, params)? {
let mut next_row = row.clone();
if bind_node(&mut next_row, chain.node.variable.as_ref(), endpoint.id)? {
if let Some(path_variable) = path_variable {
bind(
&mut next_row,
path_variable,
Binding::Path(PathBinding {
nodes: nodes.clone(),
relationships: relationships.clone(),
}),
)?;
}
next_rows.push(next_row);
}
}
}
if chain
.relationship
.max_hops
.is_some_and(|max_hops| depth >= max_hops)
{
return Ok(());
}
for relationship_id in
relationship_ids_for_direction(storage, source_id, chain.relationship.direction)
{
if path_contains_relationship(storage, relationships, relationship_id)? {
continue;
}
let relationship = storage_relationship(storage, relationship_id)?;
if !relationship_matches(storage, row, relationship, &chain.relationship, params)? {
continue;
}
let Some(endpoint_id) =
endpoint_for_direction(relationship, source_id, chain.relationship.direction)
else {
return Err(Error::Execution(format!(
"relationship {} is not connected to node {}",
relationship.id, source_id
)));
};
relationships.push(relationship_id);
nodes.push(endpoint_id);
expand_variable_length_from(
storage,
params,
chain,
row,
endpoint_id,
nodes,
relationships,
path_variable,
next_rows,
)?;
nodes.pop();
relationships.pop();
}
Ok(())
}
fn endpoint_for_direction(
relationship: &Relationship,
source_id: NodeId,
direction: Direction,
) -> Option<NodeId> {
match direction {
Direction::Outgoing if relationship.start == source_id => Some(relationship.end),
Direction::Incoming if relationship.end == source_id => Some(relationship.start),
Direction::Undirected if relationship.start == source_id => Some(relationship.end),
Direction::Undirected if relationship.end == source_id => Some(relationship.start),
_ => None,
}
}
fn node_matches(
storage: &dyn StorageInterface,
row: &Row,
node: &Node,
pattern: &NodePattern,
params: &Params,
) -> Result<bool> {
for label in &pattern.labels {
if controlled_position(storage, &node.labels, |node_label| node_label == label)?.is_none() {
return Ok(false);
}
}
properties_match(storage, row, &node.properties, &pattern.properties, params)
}
fn relationship_matches(
storage: &dyn StorageInterface,
row: &Row,
relationship: &Relationship,
pattern: &RelationshipPattern,
params: &Params,
) -> Result<bool> {
if !pattern.types.is_empty()
&& controlled_position(storage, &pattern.types, |relationship_type| {
relationship_type == &relationship.r#type
})?
.is_none()
{
return Ok(false);
}
properties_match(
storage,
row,
&relationship.properties,
&pattern.properties,
params,
)
}
fn properties_match(
storage: &dyn StorageInterface,
row: &Row,
properties: &crate::value::Properties,
predicates: &[PropertyPredicate],
params: &Params,
) -> Result<bool> {
for predicate in predicates {
let Some(actual) = properties.get(&predicate.key) else {
return Ok(false);
};
let expected = evaluate_row_expression(storage, row, &predicate.expression, params)?;
if actual != &expected {
return Ok(false);
}
}
Ok(true)
}
fn evaluate_expression(expression: &Expression, params: &Params) -> Result<Value> {
match expression {
Expression::Literal(value) => Ok(value.clone()),
Expression::Parameter(name) => params
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
Expression::Operand(Operand::Literal(value)) => Ok(value.clone()),
Expression::Operand(Operand::Parameter(name)) => params
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
Expression::Operand(_) => Err(Error::UnsupportedQueryFeature(
"row expressions are not supported in property maps".to_string(),
)),
Expression::Add(left, right) => {
let left = evaluate_expression(left, params)?;
let right = evaluate_expression(right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Add)
}
Expression::Subtract(left, right) => {
let left = evaluate_expression(left, params)?;
let right = evaluate_expression(right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Subtract)
}
Expression::Multiply(left, right) => {
let left = evaluate_expression(left, params)?;
let right = evaluate_expression(right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Multiply)
}
Expression::Divide(left, right) => {
let left = evaluate_expression(left, params)?;
let right = evaluate_expression(right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Divide)
}
Expression::Modulo(left, right) => {
let left = evaluate_expression(left, params)?;
let right = evaluate_expression(right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Modulo)
}
Expression::List(items) => items
.iter()
.map(|item| evaluate_expression(item, params))
.collect::<Result<Vec<_>>>()
.map(Value::List),
Expression::Map(entries) => entries
.iter()
.map(|(key, value)| {
evaluate_expression(value, params).map(|value| (key.clone(), value))
})
.collect::<Result<BTreeMap<_, _>>>()
.map(Value::Map),
Expression::MapProjection { .. } => Err(Error::UnsupportedQueryFeature(
"map projection requires a matched row".to_string(),
)),
Expression::PatternComprehension { .. } => Err(Error::UnsupportedQueryFeature(
"pattern comprehension requires a matched row".to_string(),
)),
Expression::Coalesce(items) => {
for item in items {
let value = evaluate_expression(item, params)?;
if value != Value::Null {
return Ok(value);
}
}
Ok(Value::Null)
}
Expression::ToLower(expression) => evaluate_string_case_value(
evaluate_expression(expression, params)?,
StringCaseFunction::Lower,
),
Expression::ToUpper(expression) => evaluate_string_case_value(
evaluate_expression(expression, params)?,
StringCaseFunction::Upper,
),
Expression::ToString(expression) => {
evaluate_to_string_value(evaluate_expression(expression, params)?)
}
Expression::ToInteger(expression) => {
evaluate_to_integer_value(evaluate_expression(expression, params)?)
}
Expression::ToFloat(expression) => {
evaluate_to_float_value(evaluate_expression(expression, params)?)
}
Expression::ToBoolean(expression) => {
evaluate_to_boolean_value(evaluate_expression(expression, params)?)
}
Expression::ToStringOrNull(expression) => {
evaluate_to_string_or_null_value(evaluate_expression(expression, params)?)
}
Expression::ToIntegerOrNull(expression) => {
evaluate_to_integer_or_null_value(evaluate_expression(expression, params)?)
}
Expression::ToFloatOrNull(expression) => {
evaluate_to_float_or_null_value(evaluate_expression(expression, params)?)
}
Expression::ToBooleanOrNull(expression) => {
evaluate_to_boolean_or_null_value(evaluate_expression(expression, params)?)
}
Expression::IsEmpty(expression) => {
evaluate_is_empty_value(evaluate_expression(expression, params)?)
}
Expression::Head(expression) => {
evaluate_head_value(evaluate_expression(expression, params)?)
}
Expression::Last(expression) => {
evaluate_last_value(evaluate_expression(expression, params)?)
}
Expression::Tail(expression) => {
evaluate_tail_value(evaluate_expression(expression, params)?)
}
Expression::Range { start, end, step } => evaluate_range_value(
evaluate_expression(start, params)?,
evaluate_expression(end, params)?,
step.as_ref()
.map(|step| evaluate_expression(step, params))
.transpose()?,
None,
),
Expression::ListIndex { value, index } => evaluate_list_index_value(
evaluate_expression(value, params)?,
evaluate_expression(index, params)?,
),
Expression::ListSlice { value, start, end } => evaluate_list_slice_value(
evaluate_expression(value, params)?,
start
.as_ref()
.map(|start| evaluate_expression(start, params))
.transpose()?,
end.as_ref()
.map(|end| evaluate_expression(end, params))
.transpose()?,
),
Expression::Size(expression) => {
evaluate_size_value(evaluate_expression(expression, params)?)
}
Expression::Substring {
value,
start,
length,
} => evaluate_substring_value(
evaluate_expression(value, params)?,
evaluate_expression(start, params)?,
length
.as_ref()
.map(|length| evaluate_expression(length, params))
.transpose()?,
),
Expression::Replace {
value,
search,
replacement,
} => evaluate_replace_value(
evaluate_expression(value, params)?,
evaluate_expression(search, params)?,
evaluate_expression(replacement, params)?,
),
Expression::Trim { mode, expression } => {
evaluate_trim_value(evaluate_expression(expression, params)?, mode)
}
Expression::Split { value, delimiter } => evaluate_split_value(
evaluate_expression(value, params)?,
evaluate_expression(delimiter, params)?,
),
Expression::StringSlice {
mode,
value,
length,
} => evaluate_string_slice_value(
evaluate_expression(value, params)?,
evaluate_expression(length, params)?,
mode,
),
Expression::Reverse(expression) => {
evaluate_reverse_value(evaluate_expression(expression, params)?)
}
Expression::Abs(expression) => evaluate_abs_value(evaluate_expression(expression, params)?),
Expression::Rounding { mode, expression } => {
evaluate_rounding_value(evaluate_expression(expression, params)?, mode)
}
Expression::Sign(expression) => {
evaluate_sign_value(evaluate_expression(expression, params)?)
}
Expression::Sqrt(expression) => {
evaluate_sqrt_value(evaluate_expression(expression, params)?)
}
Expression::Round(expression) => {
evaluate_round_value(evaluate_expression(expression, params)?)
}
Expression::Log(expression) => evaluate_log_value(evaluate_expression(expression, params)?),
Expression::Log10(expression) => {
evaluate_log10_value(evaluate_expression(expression, params)?)
}
Expression::Exp(expression) => evaluate_exp_value(evaluate_expression(expression, params)?),
Expression::AngleConversion { mode, expression } => {
evaluate_angle_conversion_value(evaluate_expression(expression, params)?, mode)
}
Expression::Trigonometric { mode, expression } => {
evaluate_trigonometric_value(evaluate_expression(expression, params)?, mode)
}
Expression::InverseTrigonometric { mode, expression } => {
evaluate_inverse_trigonometric_value(evaluate_expression(expression, params)?, mode)
}
Expression::Atan2 { y, x } => evaluate_atan2_value(
evaluate_expression(y, params)?,
evaluate_expression(x, params)?,
),
Expression::Haversin(expression) => {
evaluate_haversin_value(evaluate_expression(expression, params)?)
}
Expression::ListPredicate {
mode,
variable,
list,
predicate,
} => evaluate_list_predicate_value(
*mode,
variable,
evaluate_expression(list, params)?,
|value| evaluate_predicate_with_local(predicate, variable, value, params),
),
Expression::ListComprehension {
variable,
list,
predicate,
projection,
} => evaluate_list_comprehension_value(
evaluate_expression(list, params)?,
variable,
predicate.as_deref(),
projection,
|predicate, value| evaluate_predicate_with_local(predicate, variable, value, params),
|projection, value| evaluate_expression_with_local(projection, variable, value, params),
),
Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => evaluate_reduce_value(
evaluate_expression(list, params)?,
accumulator,
evaluate_expression(initial, params)?,
variable,
expression,
|expression, accumulator_value, item_value| {
let mut row = Row::new();
row.insert(
accumulator.clone(),
Binding::Value(accumulator_value.clone()),
);
row.insert(variable.clone(), Binding::Value(item_value.clone()));
evaluate_row_expression(&EmptyEntityLookup, &row, expression, params)
},
),
Expression::Pi => Ok(Value::Float(std::f64::consts::PI)),
Expression::E => Ok(Value::Float(std::f64::consts::E)),
Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
if evaluate_static_predicate(&alternative.predicate, params)? {
return evaluate_expression(&alternative.expression, params);
}
}
evaluate_expression(else_expression, params)
}
Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
let operand = evaluate_expression(operand, params)?;
for alternative in alternatives {
let value = evaluate_expression(&alternative.value, params)?;
if compare_values(&operand, ComparisonOperator::Equal, &value) {
return evaluate_expression(&alternative.expression, params);
}
}
evaluate_expression(else_expression, params)
}
Expression::Predicate(predicate) => {
evaluate_static_predicate(predicate, params).map(Value::Boolean)
}
}
}
fn evaluate_static_predicate(predicate: &Predicate, params: &Params) -> Result<bool> {
match predicate {
Predicate::Comparison {
left,
operator,
right,
} => {
let left = evaluate_expression(left, params)?;
let right = evaluate_expression(right, params)?;
Ok(compare_values(&left, *operator, &right))
}
Predicate::In { item, list } => {
let item = evaluate_expression(item, params)?;
let list_value = evaluate_expression(list, params)?;
evaluate_in_predicate(list, &item, &list_value, None)
}
Predicate::StringMatch {
left,
operator,
right,
} => {
let left = evaluate_expression(left, params)?;
let right = evaluate_expression(right, params)?;
evaluate_string_predicate(&left, *operator, &right)
}
Predicate::And(left, right) => {
Ok(evaluate_static_predicate(left, params)?
&& evaluate_static_predicate(right, params)?)
}
Predicate::Or(left, right) => {
Ok(evaluate_static_predicate(left, params)?
|| evaluate_static_predicate(right, params)?)
}
Predicate::Xor(left, right) => Ok(
evaluate_static_predicate(left, params)? ^ evaluate_static_predicate(right, params)?
),
Predicate::Not(inner) => Ok(!evaluate_static_predicate(inner, params)?),
Predicate::IsNull(expression) => {
Ok(evaluate_expression(expression, params)? == Value::Null)
}
Predicate::IsNotNull(expression) => {
Ok(evaluate_expression(expression, params)? != Value::Null)
}
Predicate::Boolean(expression) => match evaluate_expression(expression, params)? {
Value::Boolean(value) => Ok(value),
Value::Null => Ok(false),
_ => Err(Error::Validation(
"row count predicate must evaluate to boolean".to_string(),
)),
},
Predicate::Exists(operand) => Ok(evaluate_static_operand(operand, params)? != Value::Null),
Predicate::ExistsSubquery(_) => Err(Error::UnsupportedQueryFeature(
"row count expressions do not support EXISTS subqueries".to_string(),
)),
Predicate::Pattern(_) => Err(Error::UnsupportedQueryFeature(
"row count expressions do not support pattern predicates".to_string(),
)),
}
}
fn evaluate_static_operand(operand: &Operand, params: &Params) -> Result<Value> {
match operand {
Operand::Literal(value) => Ok(value.clone()),
Operand::Parameter(name) => params
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
Operand::Variable(variable)
| Operand::Property { variable, .. }
| Operand::DynamicProperty { variable, .. } => Err(Error::Validation(format!(
"row count expression cannot reference variable `{variable}`"
))),
}
}
fn evaluate_row_expression(
storage: &dyn StorageInterface,
row: &Row,
expression: &Expression,
params: &Params,
) -> Result<Value> {
storage.check_query_control()?;
match expression {
Expression::Literal(value) => Ok(value.clone()),
Expression::Parameter(name) => params
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
Expression::Operand(operand) => evaluate_operand(storage, row, operand, params),
Expression::Add(left, right) => {
let left = evaluate_row_expression(storage, row, left, params)?;
let right = evaluate_row_expression(storage, row, right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Add)
}
Expression::Subtract(left, right) => {
let left = evaluate_row_expression(storage, row, left, params)?;
let right = evaluate_row_expression(storage, row, right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Subtract)
}
Expression::Multiply(left, right) => {
let left = evaluate_row_expression(storage, row, left, params)?;
let right = evaluate_row_expression(storage, row, right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Multiply)
}
Expression::Divide(left, right) => {
let left = evaluate_row_expression(storage, row, left, params)?;
let right = evaluate_row_expression(storage, row, right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Divide)
}
Expression::Modulo(left, right) => {
let left = evaluate_row_expression(storage, row, left, params)?;
let right = evaluate_row_expression(storage, row, right, params)?;
evaluate_arithmetic_values(&left, &right, ArithmeticOperator::Modulo)
}
Expression::List(items) => items
.iter()
.map(|item| evaluate_row_expression(storage, row, item, params))
.collect::<Result<Vec<_>>>()
.map(Value::List),
Expression::Map(entries) => entries
.iter()
.map(|(key, value)| {
evaluate_row_expression(storage, row, value, params)
.map(|value| (key.clone(), value))
})
.collect::<Result<BTreeMap<_, _>>>()
.map(Value::Map),
Expression::MapProjection { variable, items } => {
evaluate_map_projection_value(storage, row, variable, items, params)
}
Expression::Coalesce(items) => {
for item in items {
let value = evaluate_row_expression(storage, row, item, params)?;
if value != Value::Null {
return Ok(value);
}
}
Ok(Value::Null)
}
Expression::ToLower(expression) => evaluate_string_case_value(
evaluate_row_expression(storage, row, expression, params)?,
StringCaseFunction::Lower,
),
Expression::ToUpper(expression) => evaluate_string_case_value(
evaluate_row_expression(storage, row, expression, params)?,
StringCaseFunction::Upper,
),
Expression::ToString(expression) => {
evaluate_to_string_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::ToInteger(expression) => {
evaluate_to_integer_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::ToFloat(expression) => {
evaluate_to_float_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::ToBoolean(expression) => {
evaluate_to_boolean_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::ToStringOrNull(expression) => evaluate_to_string_or_null_value(
evaluate_row_expression(storage, row, expression, params)?,
),
Expression::ToIntegerOrNull(expression) => evaluate_to_integer_or_null_value(
evaluate_row_expression(storage, row, expression, params)?,
),
Expression::ToFloatOrNull(expression) => evaluate_to_float_or_null_value(
evaluate_row_expression(storage, row, expression, params)?,
),
Expression::ToBooleanOrNull(expression) => evaluate_to_boolean_or_null_value(
evaluate_row_expression(storage, row, expression, params)?,
),
Expression::IsEmpty(expression) => {
evaluate_is_empty_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Head(expression) => {
evaluate_head_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Last(expression) => {
evaluate_last_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Tail(expression) => {
evaluate_tail_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Range { start, end, step } => evaluate_range_value(
evaluate_row_expression(storage, row, start, params)?,
evaluate_row_expression(storage, row, end, params)?,
step.as_ref()
.map(|step| evaluate_row_expression(storage, row, step, params))
.transpose()?,
Some(storage),
),
Expression::ListIndex { value, index } => evaluate_list_index_value(
evaluate_row_expression(storage, row, value, params)?,
evaluate_row_expression(storage, row, index, params)?,
),
Expression::ListSlice { value, start, end } => evaluate_list_slice_value(
evaluate_row_expression(storage, row, value, params)?,
start
.as_ref()
.map(|start| evaluate_row_expression(storage, row, start, params))
.transpose()?,
end.as_ref()
.map(|end| evaluate_row_expression(storage, row, end, params))
.transpose()?,
),
Expression::Size(expression) => {
evaluate_size_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Substring {
value,
start,
length,
} => evaluate_substring_value(
evaluate_row_expression(storage, row, value, params)?,
evaluate_row_expression(storage, row, start, params)?,
length
.as_ref()
.map(|length| evaluate_row_expression(storage, row, length, params))
.transpose()?,
),
Expression::Replace {
value,
search,
replacement,
} => evaluate_replace_value(
evaluate_row_expression(storage, row, value, params)?,
evaluate_row_expression(storage, row, search, params)?,
evaluate_row_expression(storage, row, replacement, params)?,
),
Expression::Trim { mode, expression } => evaluate_trim_value(
evaluate_row_expression(storage, row, expression, params)?,
mode,
),
Expression::Split { value, delimiter } => evaluate_split_value(
evaluate_row_expression(storage, row, value, params)?,
evaluate_row_expression(storage, row, delimiter, params)?,
),
Expression::StringSlice {
mode,
value,
length,
} => evaluate_string_slice_value(
evaluate_row_expression(storage, row, value, params)?,
evaluate_row_expression(storage, row, length, params)?,
mode,
),
Expression::Reverse(expression) => {
evaluate_reverse_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Abs(expression) => {
evaluate_abs_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Rounding { mode, expression } => evaluate_rounding_value(
evaluate_row_expression(storage, row, expression, params)?,
mode,
),
Expression::Sign(expression) => {
evaluate_sign_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Sqrt(expression) => {
evaluate_sqrt_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Round(expression) => {
evaluate_round_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Log(expression) => {
evaluate_log_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Log10(expression) => {
evaluate_log10_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::Exp(expression) => {
evaluate_exp_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::AngleConversion { mode, expression } => evaluate_angle_conversion_value(
evaluate_row_expression(storage, row, expression, params)?,
mode,
),
Expression::Trigonometric { mode, expression } => evaluate_trigonometric_value(
evaluate_row_expression(storage, row, expression, params)?,
mode,
),
Expression::InverseTrigonometric { mode, expression } => {
evaluate_inverse_trigonometric_value(
evaluate_row_expression(storage, row, expression, params)?,
mode,
)
}
Expression::Atan2 { y, x } => evaluate_atan2_value(
evaluate_row_expression(storage, row, y, params)?,
evaluate_row_expression(storage, row, x, params)?,
),
Expression::Haversin(expression) => {
evaluate_haversin_value(evaluate_row_expression(storage, row, expression, params)?)
}
Expression::ListPredicate {
mode,
variable,
list,
predicate,
} => evaluate_list_predicate_value(
*mode,
variable,
evaluate_row_expression(storage, row, list, params)?,
|value| {
evaluate_row_predicate_with_local(storage, row, predicate, variable, value, params)
},
),
Expression::ListComprehension {
variable,
list,
predicate,
projection,
} => evaluate_list_comprehension_value(
evaluate_row_expression(storage, row, list, params)?,
variable,
predicate.as_deref(),
projection,
|predicate, value| {
evaluate_row_predicate_with_local(storage, row, predicate, variable, value, params)
},
|projection, value| {
evaluate_row_expression_with_local(
storage, row, projection, variable, value, params,
)
},
),
Expression::PatternComprehension {
pattern,
predicate,
projection,
} => evaluate_pattern_comprehension_value(
storage,
row,
pattern,
predicate.as_deref(),
projection,
params,
),
Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => evaluate_reduce_value(
evaluate_row_expression(storage, row, list, params)?,
accumulator,
evaluate_row_expression(storage, row, initial, params)?,
variable,
expression,
|expression, accumulator_value, item_value| {
let mut row = row.clone();
row.insert(
accumulator.clone(),
Binding::Value(accumulator_value.clone()),
);
row.insert(variable.clone(), Binding::Value(item_value.clone()));
evaluate_row_expression(storage, &row, expression, params)
},
),
Expression::Pi => Ok(Value::Float(std::f64::consts::PI)),
Expression::E => Ok(Value::Float(std::f64::consts::E)),
Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
if evaluate_predicate(storage, row, &alternative.predicate, params)? {
return evaluate_row_expression(storage, row, &alternative.expression, params);
}
}
evaluate_row_expression(storage, row, else_expression, params)
}
Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
let operand = evaluate_row_expression(storage, row, operand, params)?;
for alternative in alternatives {
let value = evaluate_row_expression(storage, row, &alternative.value, params)?;
if compare_values(&operand, ComparisonOperator::Equal, &value) {
return evaluate_row_expression(storage, row, &alternative.expression, params);
}
}
evaluate_row_expression(storage, row, else_expression, params)
}
Expression::Predicate(predicate) => {
evaluate_predicate(storage, row, predicate, params).map(Value::Boolean)
}
}
}
#[derive(Clone, Copy)]
enum StringCaseFunction {
Lower,
Upper,
}
fn evaluate_string_case_value(value: Value, function: StringCaseFunction) -> Result<Value> {
match value {
Value::String(value) => Ok(Value::String(match function {
StringCaseFunction::Lower => value.to_lowercase(),
StringCaseFunction::Upper => value.to_uppercase(),
})),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"string case functions require string arguments".to_string(),
)),
}
}
fn evaluate_to_string_value(value: Value) -> Result<Value> {
match value {
Value::String(value) => Ok(Value::String(value)),
Value::Integer(value) => Ok(Value::String(value.to_string())),
Value::Float(value) => Ok(Value::String(value.to_string())),
Value::Boolean(value) => Ok(Value::String(value.to_string())),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"toString function requires a scalar argument".to_string(),
)),
}
}
fn evaluate_to_integer_value(value: Value) -> Result<Value> {
match value {
Value::Integer(value) => Ok(Value::Integer(value)),
Value::Float(value) => Ok(Value::Integer(value as i64)),
Value::String(value) => Ok(value
.parse::<i64>()
.map(Value::Integer)
.unwrap_or(Value::Null)),
Value::Boolean(value) => Ok(Value::Integer(if value { 1 } else { 0 })),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"toInteger function requires a scalar argument".to_string(),
)),
}
}
fn evaluate_to_float_value(value: Value) -> Result<Value> {
match value {
Value::Float(value) => Ok(Value::Float(value)),
Value::Integer(value) => Ok(Value::Float(value as f64)),
Value::String(value) => Ok(value
.parse::<f64>()
.map(Value::Float)
.unwrap_or(Value::Null)),
Value::Boolean(value) => Ok(Value::Float(if value { 1.0 } else { 0.0 })),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"toFloat function requires a scalar argument".to_string(),
)),
}
}
fn evaluate_to_boolean_value(value: Value) -> Result<Value> {
match value {
Value::Boolean(value) => Ok(Value::Boolean(value)),
Value::Integer(value) => Ok(Value::Boolean(value != 0)),
Value::String(value) => match value.to_ascii_lowercase().as_str() {
"true" => Ok(Value::Boolean(true)),
"false" => Ok(Value::Boolean(false)),
_ => Ok(Value::Null),
},
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"toBoolean function requires a scalar argument".to_string(),
)),
}
}
fn evaluate_to_string_or_null_value(value: Value) -> Result<Value> {
match evaluate_to_string_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_to_integer_or_null_value(value: Value) -> Result<Value> {
match evaluate_to_integer_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_to_float_or_null_value(value: Value) -> Result<Value> {
match evaluate_to_float_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_to_boolean_or_null_value(value: Value) -> Result<Value> {
match evaluate_to_boolean_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_is_empty_value(value: Value) -> Result<Value> {
match value {
Value::String(value) => Ok(Value::Boolean(value.is_empty())),
Value::List(values) => Ok(Value::Boolean(values.is_empty())),
Value::Map(values) => Ok(Value::Boolean(values.is_empty())),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"isEmpty function requires string, list, or map arguments".to_string(),
)),
}
}
fn evaluate_head_value(value: Value) -> Result<Value> {
match value {
Value::List(values) => Ok(values.into_iter().next().unwrap_or(Value::Null)),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"head function requires a list argument".to_string(),
)),
}
}
fn evaluate_last_value(value: Value) -> Result<Value> {
match value {
Value::List(values) => Ok(values.into_iter().last().unwrap_or(Value::Null)),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"last function requires a list argument".to_string(),
)),
}
}
fn evaluate_tail_value(value: Value) -> Result<Value> {
match value {
Value::List(values) => Ok(Value::List(values.into_iter().skip(1).collect())),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"tail function requires a list argument".to_string(),
)),
}
}
fn evaluate_range_value(
start: Value,
end: Value,
step: Option<Value>,
storage: Option<&dyn StorageInterface>,
) -> Result<Value> {
if matches!(start, Value::Null)
|| matches!(end, Value::Null)
|| step
.as_ref()
.is_some_and(|step| matches!(step, Value::Null))
{
return Ok(Value::Null);
}
let Value::Integer(start) = start else {
return Err(Error::Validation(
"range function requires integer arguments".to_string(),
));
};
let Value::Integer(end) = end else {
return Err(Error::Validation(
"range function requires integer arguments".to_string(),
));
};
let step = match step {
Some(Value::Integer(step)) => step,
Some(_) => {
return Err(Error::Validation(
"range function requires integer arguments".to_string(),
))
}
None => 1,
};
if step == 0 {
return Err(Error::Validation(
"range function step cannot be zero".to_string(),
));
}
let mut values = Vec::new();
let mut current = start;
if step > 0 {
while current <= end {
if values.len() % QUERY_CONTROL_COMPARISON_BATCH == 0 {
if let Some(storage) = storage {
storage.check_query_control()?;
}
}
values.push(Value::Integer(current));
let Some(next) = current.checked_add(step) else {
break;
};
current = next;
}
} else {
while current >= end {
if values.len() % QUERY_CONTROL_COMPARISON_BATCH == 0 {
if let Some(storage) = storage {
storage.check_query_control()?;
}
}
values.push(Value::Integer(current));
let Some(next) = current.checked_add(step) else {
break;
};
current = next;
}
}
Ok(Value::List(values))
}
fn evaluate_list_index_value(value: Value, index: Value) -> Result<Value> {
if matches!(value, Value::Null) || matches!(index, Value::Null) {
return Ok(Value::Null);
}
let Value::List(values) = value else {
return Err(Error::Validation(
"list index expression requires a list value".to_string(),
));
};
let Value::Integer(index) = index else {
return Err(Error::Validation(
"list index expression requires an integer index".to_string(),
));
};
let index = if index < 0 {
values.len() as i64 + index
} else {
index
};
if index < 0 {
return Ok(Value::Null);
}
Ok(values.get(index as usize).cloned().unwrap_or(Value::Null))
}
fn evaluate_list_slice_value(
value: Value,
start: Option<Value>,
end: Option<Value>,
) -> Result<Value> {
if matches!(value, Value::Null)
|| start
.as_ref()
.is_some_and(|start| matches!(start, Value::Null))
|| end.as_ref().is_some_and(|end| matches!(end, Value::Null))
{
return Ok(Value::Null);
}
let Value::List(values) = value else {
return Err(Error::Validation(
"list slice expression requires a list value".to_string(),
));
};
let start = match start {
Some(Value::Integer(start)) => normalize_slice_bound(start, values.len()),
Some(_) => {
return Err(Error::Validation(
"list slice expression requires integer bounds".to_string(),
))
}
None => 0,
};
let end = match end {
Some(Value::Integer(end)) => normalize_slice_bound(end, values.len()),
Some(_) => {
return Err(Error::Validation(
"list slice expression requires integer bounds".to_string(),
))
}
None => values.len(),
};
if start >= end {
return Ok(Value::List(Vec::new()));
}
Ok(Value::List(values[start..end].to_vec()))
}
fn normalize_slice_bound(bound: i64, len: usize) -> usize {
let len = len as i64;
let bound = if bound < 0 { len + bound } else { bound };
bound.clamp(0, len) as usize
}
fn evaluate_size_value(value: Value) -> Result<Value> {
match value {
Value::String(value) => Ok(Value::Integer(value.chars().count() as i64)),
Value::List(values) => Ok(Value::Integer(values.len() as i64)),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"size function requires string or list arguments".to_string(),
)),
}
}
fn evaluate_substring_value(value: Value, start: Value, length: Option<Value>) -> Result<Value> {
if matches!(value, Value::Null)
|| matches!(start, Value::Null)
|| length
.as_ref()
.is_some_and(|length| matches!(length, Value::Null))
{
return Ok(Value::Null);
}
let Value::String(value) = value else {
return Err(Error::Validation(
"substring function requires a string value".to_string(),
));
};
let Value::Integer(start) = start else {
return Err(Error::Validation(
"substring start must be an integer".to_string(),
));
};
if start < 0 {
return Err(Error::Validation(
"substring start must be non-negative".to_string(),
));
}
let length = match length {
Some(Value::Integer(length)) if length >= 0 => Some(length as usize),
Some(Value::Integer(_)) => {
return Err(Error::Validation(
"substring length must be non-negative".to_string(),
))
}
Some(_) => {
return Err(Error::Validation(
"substring length must be an integer".to_string(),
))
}
None => None,
};
let chars = value.chars().skip(start as usize);
let substring = match length {
Some(length) => chars.take(length).collect(),
None => chars.collect(),
};
Ok(Value::String(substring))
}
fn evaluate_replace_value(value: Value, search: Value, replacement: Value) -> Result<Value> {
if matches!(value, Value::Null)
|| matches!(search, Value::Null)
|| matches!(replacement, Value::Null)
{
return Ok(Value::Null);
}
let Value::String(value) = value else {
return Err(Error::Validation(
"replace function requires a string value".to_string(),
));
};
let Value::String(search) = search else {
return Err(Error::Validation(
"replace search must be a string".to_string(),
));
};
let Value::String(replacement) = replacement else {
return Err(Error::Validation(
"replace replacement must be a string".to_string(),
));
};
Ok(Value::String(value.replace(&search, &replacement)))
}
fn evaluate_trim_value(value: Value, mode: &TrimMode) -> Result<Value> {
match value {
Value::String(value) => Ok(Value::String(match mode {
TrimMode::Both => value.trim().to_string(),
TrimMode::Left => value.trim_start().to_string(),
TrimMode::Right => value.trim_end().to_string(),
})),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"trim functions require string arguments".to_string(),
)),
}
}
fn evaluate_split_value(value: Value, delimiter: Value) -> Result<Value> {
if matches!(value, Value::Null) || matches!(delimiter, Value::Null) {
return Ok(Value::Null);
}
let Value::String(value) = value else {
return Err(Error::Validation(
"split function requires a string value".to_string(),
));
};
let Value::String(delimiter) = delimiter else {
return Err(Error::Validation(
"split delimiter must be a string".to_string(),
));
};
Ok(Value::List(
value
.split(&delimiter)
.map(|part| Value::String(part.to_string()))
.collect(),
))
}
fn evaluate_string_slice_value(
value: Value,
length: Value,
mode: &StringSliceMode,
) -> Result<Value> {
if matches!(value, Value::Null) || matches!(length, Value::Null) {
return Ok(Value::Null);
}
let Value::String(value) = value else {
return Err(Error::Validation(
"left and right functions require a string value".to_string(),
));
};
let Value::Integer(length) = length else {
return Err(Error::Validation(
"left and right length must be an integer".to_string(),
));
};
if length < 0 {
return Err(Error::Validation(
"left and right length must be non-negative".to_string(),
));
}
let length = length as usize;
let value = match mode {
StringSliceMode::Left => value.chars().take(length).collect(),
StringSliceMode::Right => {
let chars = value.chars().collect::<Vec<_>>();
chars
.iter()
.skip(chars.len().saturating_sub(length))
.collect()
}
};
Ok(Value::String(value))
}
fn evaluate_reverse_value(value: Value) -> Result<Value> {
match value {
Value::String(value) => Ok(Value::String(value.chars().rev().collect())),
Value::List(mut values) => {
values.reverse();
Ok(Value::List(values))
}
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"reverse function requires a string or list argument".to_string(),
)),
}
}
fn evaluate_abs_value(value: Value) -> Result<Value> {
match value {
Value::Integer(value) => value
.checked_abs()
.map(Value::Integer)
.ok_or_else(|| Error::Execution("integer abs result exceeds i64 range".to_string())),
Value::Float(value) => Ok(Value::Float(value.abs())),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"abs function requires a numeric argument".to_string(),
)),
}
}
fn evaluate_rounding_value(value: Value, mode: &RoundingMode) -> Result<Value> {
match value {
Value::Integer(value) => Ok(Value::Integer(value)),
Value::Float(value) => Ok(Value::Float(match mode {
RoundingMode::Ceil => value.ceil(),
RoundingMode::Floor => value.floor(),
})),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"ceil and floor functions require numeric arguments".to_string(),
)),
}
}
fn evaluate_sign_value(value: Value) -> Result<Value> {
match value {
Value::Integer(value) => Ok(Value::Integer(value.signum())),
Value::Float(value) => Ok(Value::Integer(if value > 0.0 {
1
} else if value < 0.0 {
-1
} else {
0
})),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"sign function requires a numeric argument".to_string(),
)),
}
}
fn evaluate_sqrt_value(value: Value) -> Result<Value> {
let value = match value {
Value::Integer(value) => value as f64,
Value::Float(value) => value,
Value::Null => return Ok(Value::Null),
_ => {
return Err(Error::Validation(
"sqrt function requires a numeric argument".to_string(),
))
}
};
if value < 0.0 {
return Err(Error::Validation(
"sqrt function requires a non-negative argument".to_string(),
));
}
Ok(Value::Float(value.sqrt()))
}
fn evaluate_round_value(value: Value) -> Result<Value> {
match value {
Value::Integer(value) => Ok(Value::Float(value as f64)),
Value::Float(value) => Ok(Value::Float(value.round())),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"round function requires a numeric argument".to_string(),
)),
}
}
fn evaluate_log_value(value: Value) -> Result<Value> {
let value = match value {
Value::Integer(value) => value as f64,
Value::Float(value) => value,
Value::Null => return Ok(Value::Null),
_ => {
return Err(Error::Validation(
"log function requires a numeric argument".to_string(),
))
}
};
if value <= 0.0 {
return Err(Error::Validation(
"log function requires a positive argument".to_string(),
));
}
Ok(Value::Float(value.ln()))
}
fn evaluate_log10_value(value: Value) -> Result<Value> {
let value = match value {
Value::Integer(value) => value as f64,
Value::Float(value) => value,
Value::Null => return Ok(Value::Null),
_ => {
return Err(Error::Validation(
"log10 function requires a numeric argument".to_string(),
))
}
};
if value <= 0.0 {
return Err(Error::Validation(
"log10 function requires a positive argument".to_string(),
));
}
Ok(Value::Float(value.log10()))
}
fn evaluate_exp_value(value: Value) -> Result<Value> {
match value {
Value::Integer(value) => Ok(Value::Float((value as f64).exp())),
Value::Float(value) => Ok(Value::Float(value.exp())),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"exp function requires a numeric argument".to_string(),
)),
}
}
fn evaluate_angle_conversion_value(value: Value, mode: &AngleConversionMode) -> Result<Value> {
let value = match value {
Value::Integer(value) => value as f64,
Value::Float(value) => value,
Value::Null => return Ok(Value::Null),
_ => {
return Err(Error::Validation(
"degrees and radians functions require numeric arguments".to_string(),
))
}
};
Ok(Value::Float(match mode {
AngleConversionMode::Degrees => value.to_degrees(),
AngleConversionMode::Radians => value.to_radians(),
}))
}
fn evaluate_trigonometric_value(value: Value, mode: &TrigonometricMode) -> Result<Value> {
let value = match value {
Value::Integer(value) => value as f64,
Value::Float(value) => value,
Value::Null => return Ok(Value::Null),
_ => {
return Err(Error::Validation(
"trigonometric functions require numeric arguments".to_string(),
))
}
};
Ok(Value::Float(match mode {
TrigonometricMode::Sin => value.sin(),
TrigonometricMode::Cos => value.cos(),
TrigonometricMode::Tan => value.tan(),
TrigonometricMode::Cot => 1.0 / value.tan(),
}))
}
fn evaluate_inverse_trigonometric_value(
value: Value,
mode: &InverseTrigonometricMode,
) -> Result<Value> {
let value = match value {
Value::Integer(value) => value as f64,
Value::Float(value) => value,
Value::Null => return Ok(Value::Null),
_ => {
return Err(Error::Validation(
"inverse trigonometric functions require numeric arguments".to_string(),
))
}
};
Ok(Value::Float(match mode {
InverseTrigonometricMode::Acos => value.acos(),
InverseTrigonometricMode::Asin => value.asin(),
InverseTrigonometricMode::Atan => value.atan(),
}))
}
fn evaluate_atan2_value(y: Value, x: Value) -> Result<Value> {
if y == Value::Null || x == Value::Null {
return Ok(Value::Null);
}
let y = numeric_argument_value(y, "atan2")?;
let x = numeric_argument_value(x, "atan2")?;
Ok(Value::Float(y.atan2(x)))
}
fn evaluate_haversin_value(value: Value) -> Result<Value> {
let value = match value {
Value::Integer(value) => value as f64,
Value::Float(value) => value,
Value::Null => return Ok(Value::Null),
_ => {
return Err(Error::Validation(
"haversin function requires a numeric argument".to_string(),
))
}
};
let sine = (value / 2.0).sin();
Ok(Value::Float(sine * sine))
}
fn numeric_argument_value(value: Value, function: &str) -> Result<f64> {
match value {
Value::Integer(value) => Ok(value as f64),
Value::Float(value) => Ok(value),
_ => Err(Error::Validation(format!(
"{function} function requires numeric arguments"
))),
}
}
#[derive(Clone, Copy)]
enum ArithmeticOperator {
Add,
Subtract,
Multiply,
Divide,
Modulo,
}
fn evaluate_arithmetic_values(
left: &Value,
right: &Value,
operator: ArithmeticOperator,
) -> Result<Value> {
match (left, right, operator) {
(Value::Integer(left), Value::Integer(right), ArithmeticOperator::Add) => {
left.checked_add(*right).map(Value::Integer).ok_or_else(|| {
Error::Execution("integer addition result exceeds i64 range".to_string())
})
}
(Value::String(left), Value::String(right), ArithmeticOperator::Add) => {
Ok(Value::String(format!("{left}{right}")))
}
(Value::List(left), Value::List(right), ArithmeticOperator::Add) => {
let mut values = left.clone();
values.extend(right.clone());
Ok(Value::List(values))
}
(Value::Integer(left), Value::Integer(right), ArithmeticOperator::Subtract) => {
left.checked_sub(*right).map(Value::Integer).ok_or_else(|| {
Error::Execution("integer subtraction result exceeds i64 range".to_string())
})
}
(Value::Integer(left), Value::Integer(right), ArithmeticOperator::Multiply) => {
left.checked_mul(*right).map(Value::Integer).ok_or_else(|| {
Error::Execution("integer multiplication result exceeds i64 range".to_string())
})
}
(Value::Integer(_), Value::Integer(0), ArithmeticOperator::Divide) => {
Err(Error::Validation("division by zero".to_string()))
}
(Value::Integer(left), Value::Integer(right), ArithmeticOperator::Divide) => {
Ok(Value::Float(*left as f64 / *right as f64))
}
(Value::Integer(_), Value::Integer(0), ArithmeticOperator::Modulo) => {
Err(Error::Validation("modulo by zero".to_string()))
}
(Value::Integer(left), Value::Integer(right), ArithmeticOperator::Modulo) => {
Ok(Value::Integer(left % right))
}
(Value::Integer(left), Value::Float(right), operator) => {
evaluate_float_arithmetic(*left as f64, *right, operator)
}
(Value::Float(left), Value::Integer(right), operator) => {
evaluate_float_arithmetic(*left, *right as f64, operator)
}
(Value::Float(left), Value::Float(right), operator) => {
evaluate_float_arithmetic(*left, *right, operator)
}
_ => Err(Error::Validation(
"arithmetic operators require numeric operands".to_string(),
)),
}
}
fn evaluate_float_arithmetic(left: f64, right: f64, operator: ArithmeticOperator) -> Result<Value> {
match operator {
ArithmeticOperator::Add => Ok(Value::Float(left + right)),
ArithmeticOperator::Subtract => Ok(Value::Float(left - right)),
ArithmeticOperator::Multiply => Ok(Value::Float(left * right)),
ArithmeticOperator::Divide if right == 0.0 => {
Err(Error::Validation("division by zero".to_string()))
}
ArithmeticOperator::Divide => Ok(Value::Float(left / right)),
ArithmeticOperator::Modulo if right == 0.0 => {
Err(Error::Validation("modulo by zero".to_string()))
}
ArithmeticOperator::Modulo => Ok(Value::Float(left % right)),
}
}
fn evaluate_predicate(
storage: &dyn StorageInterface,
row: &Row,
predicate: &Predicate,
params: &Params,
) -> Result<bool> {
storage.check_query_control()?;
match predicate {
Predicate::Comparison {
left,
operator,
right,
} => {
let left = evaluate_row_expression(storage, row, left, params)?;
let right = evaluate_row_expression(storage, row, right, params)?;
Ok(compare_values(&left, *operator, &right))
}
Predicate::In { item, list } => {
let item = evaluate_row_expression(storage, row, item, params)?;
let list_value = evaluate_row_expression(storage, row, list, params)?;
evaluate_in_predicate(list, &item, &list_value, Some(storage))
}
Predicate::StringMatch {
left,
operator,
right,
} => {
let left = evaluate_row_expression(storage, row, left, params)?;
let right = evaluate_row_expression(storage, row, right, params)?;
evaluate_string_predicate(&left, *operator, &right)
}
Predicate::And(left, right) => Ok(evaluate_predicate(storage, row, left, params)?
&& evaluate_predicate(storage, row, right, params)?),
Predicate::Or(left, right) => Ok(evaluate_predicate(storage, row, left, params)?
|| evaluate_predicate(storage, row, right, params)?),
Predicate::Xor(left, right) => Ok(evaluate_predicate(storage, row, left, params)?
^ evaluate_predicate(storage, row, right, params)?),
Predicate::Not(inner) => Ok(!evaluate_predicate(storage, row, inner, params)?),
Predicate::Pattern(pattern) => evaluate_pattern_predicate(storage, row, pattern, params),
Predicate::IsNull(expression) => {
Ok(evaluate_row_expression(storage, row, expression, params)? == Value::Null)
}
Predicate::IsNotNull(expression) => {
Ok(evaluate_row_expression(storage, row, expression, params)? != Value::Null)
}
Predicate::Exists(operand) => {
Ok(evaluate_operand(storage, row, operand, params)? != Value::Null)
}
Predicate::ExistsSubquery(matches) => {
evaluate_exists_subquery(storage, row, matches, params)
}
Predicate::Boolean(expression) => {
match evaluate_row_expression(storage, row, expression, params)? {
Value::Boolean(value) => Ok(value),
Value::Null => Ok(false),
_ => Err(Error::Validation(
"WHERE bare operands must evaluate to boolean".to_string(),
)),
}
}
}
}
fn evaluate_exists_subquery(
storage: &dyn StorageInterface,
row: &Row,
matches: &[MatchClause],
params: &Params,
) -> Result<bool> {
let mut rows = vec![row.clone()];
for clause in matches {
rows = apply_match_clause(storage, params, rows, clause)?;
if rows.is_empty() {
return Ok(false);
}
}
Ok(!rows.is_empty())
}
fn evaluate_pattern_predicate(
storage: &dyn StorageInterface,
row: &Row,
pattern: &Pattern,
params: &Params,
) -> Result<bool> {
let Some(chain) = pattern.chains.first() else {
return Ok(false);
};
let start_binding = pattern
.start
.variable
.as_deref()
.and_then(|variable| row.get(variable));
let end_binding = chain
.node
.variable
.as_deref()
.and_then(|variable| row.get(variable));
let start_id = match start_binding {
Some(Binding::Node(node_id)) => Some(*node_id),
Some(_) => return Ok(false),
None => None,
};
let end_id = match end_binding {
Some(Binding::Node(node_id)) => Some(*node_id),
Some(_) => return Ok(false),
None => None,
};
let anchor_id = start_id.or(end_id).ok_or_else(|| {
Error::Execution("pattern predicate is missing a bound endpoint".to_string())
})?;
let relationship_ids = match (start_id.is_some(), chain.relationship.direction) {
(true, Direction::Outgoing) | (false, Direction::Incoming) => {
storage.outgoing_relationships(anchor_id).to_vec()
}
(true, Direction::Incoming) | (false, Direction::Outgoing) => {
storage.incoming_relationships(anchor_id).to_vec()
}
(_, Direction::Undirected) => storage
.outgoing_relationships(anchor_id)
.iter()
.chain(storage.incoming_relationships(anchor_id))
.copied()
.collect::<Vec<_>>(),
};
for relationship_id in relationship_ids {
let relationship = storage_relationship(storage, relationship_id)?;
if !relationship_matches(storage, row, relationship, &chain.relationship, params)? {
continue;
}
if let Some(variable) = &chain.relationship.variable {
match row.get(variable) {
Some(Binding::Relationship(bound_id)) if *bound_id == relationship_id => {}
Some(Binding::Relationship(_)) => continue,
Some(_) => return Ok(false),
None => {
return Err(Error::Execution(format!(
"pattern predicate relationship variable `{variable}` is not bound"
)))
}
}
}
let (candidate_start, candidate_end) = match chain.relationship.direction {
Direction::Outgoing => (relationship.start, relationship.end),
Direction::Incoming => (relationship.end, relationship.start),
Direction::Undirected => {
if start_id == Some(relationship.start) || end_id == Some(relationship.end) {
(relationship.start, relationship.end)
} else {
(relationship.end, relationship.start)
}
}
};
if start_id.is_some_and(|node_id| node_id != candidate_start)
|| end_id.is_some_and(|node_id| node_id != candidate_end)
{
continue;
}
let start_node = storage_node(storage, candidate_start)?;
let end_node = storage_node(storage, candidate_end)?;
if node_matches(storage, row, start_node, &pattern.start, params)?
&& node_matches(storage, row, end_node, &chain.node, params)?
{
return Ok(true);
}
}
Ok(false)
}
fn evaluate_list_predicate_value(
mode: ListPredicateMode,
variable: &str,
list: Value,
mut predicate: impl FnMut(&Value) -> Result<bool>,
) -> Result<Value> {
let _ = variable;
let Value::List(values) = list else {
return if list == Value::Null {
Ok(Value::Null)
} else {
Err(Error::Validation(
"list predicate functions require a list argument".to_string(),
))
};
};
let mut matches = 0usize;
for value in &values {
if predicate(value)? {
matches += 1;
}
}
Ok(Value::Boolean(match mode {
ListPredicateMode::All => matches == values.len(),
ListPredicateMode::Any => matches > 0,
ListPredicateMode::None => matches == 0,
ListPredicateMode::Single => matches == 1,
}))
}
fn evaluate_list_comprehension_value(
list: Value,
variable: &str,
predicate: Option<&Predicate>,
projection: &Expression,
mut evaluate_predicate: impl FnMut(&Predicate, &Value) -> Result<bool>,
mut evaluate_projection: impl FnMut(&Expression, &Value) -> Result<Value>,
) -> Result<Value> {
let _ = variable;
let Value::List(values) = list else {
return if list == Value::Null {
Ok(Value::Null)
} else {
Err(Error::Validation(
"list comprehension requires a list argument".to_string(),
))
};
};
let mut output = Vec::new();
for value in values {
if predicate
.map(|predicate| evaluate_predicate(predicate, &value))
.transpose()?
.unwrap_or(true)
{
output.push(evaluate_projection(projection, &value)?);
}
}
Ok(Value::List(output))
}
fn evaluate_reduce_value(
list: Value,
accumulator: &str,
initial: Value,
variable: &str,
expression: &Expression,
mut evaluate_expression: impl FnMut(&Expression, &Value, &Value) -> Result<Value>,
) -> Result<Value> {
let _ = (accumulator, variable);
let Value::List(values) = list else {
return if list == Value::Null {
Ok(Value::Null)
} else {
Err(Error::Validation(
"reduce requires a list argument".to_string(),
))
};
};
let mut accumulator_value = initial;
for value in values {
accumulator_value = evaluate_expression(expression, &accumulator_value, &value)?;
}
Ok(accumulator_value)
}
fn evaluate_row_expression_with_local(
storage: &dyn StorageInterface,
row: &Row,
expression: &Expression,
variable: &str,
value: &Value,
params: &Params,
) -> Result<Value> {
let mut row = row.clone();
row.insert(variable.to_string(), Binding::Value(value.clone()));
evaluate_row_expression(storage, &row, expression, params)
}
fn evaluate_expression_with_local(
expression: &Expression,
variable: &str,
value: &Value,
params: &Params,
) -> Result<Value> {
let mut row = Row::new();
row.insert(variable.to_string(), Binding::Value(value.clone()));
evaluate_row_expression(&EmptyEntityLookup, &row, expression, params)
}
fn evaluate_row_predicate_with_local(
storage: &dyn StorageInterface,
row: &Row,
predicate: &Predicate,
variable: &str,
value: &Value,
params: &Params,
) -> Result<bool> {
match predicate {
Predicate::Comparison {
left,
operator,
right,
} => {
let left =
evaluate_row_expression_with_local(storage, row, left, variable, value, params)?;
let right =
evaluate_row_expression_with_local(storage, row, right, variable, value, params)?;
Ok(compare_values(&left, *operator, &right))
}
Predicate::In { item, list } => {
let item =
evaluate_row_expression_with_local(storage, row, item, variable, value, params)?;
let list_value =
evaluate_row_expression_with_local(storage, row, list, variable, value, params)?;
evaluate_in_predicate(list, &item, &list_value, Some(storage))
}
Predicate::StringMatch {
left,
operator,
right,
} => {
let left =
evaluate_row_expression_with_local(storage, row, left, variable, value, params)?;
let right =
evaluate_row_expression_with_local(storage, row, right, variable, value, params)?;
evaluate_string_predicate(&left, *operator, &right)
}
Predicate::And(left, right) => Ok(evaluate_row_predicate_with_local(
storage, row, left, variable, value, params,
)? && evaluate_row_predicate_with_local(
storage, row, right, variable, value, params,
)?),
Predicate::Or(left, right) => Ok(evaluate_row_predicate_with_local(
storage, row, left, variable, value, params,
)? || evaluate_row_predicate_with_local(
storage, row, right, variable, value, params,
)?),
Predicate::Xor(left, right) => Ok(evaluate_row_predicate_with_local(
storage, row, left, variable, value, params,
)? ^ evaluate_row_predicate_with_local(
storage, row, right, variable, value, params,
)?),
Predicate::Not(inner) => Ok(!evaluate_row_predicate_with_local(
storage, row, inner, variable, value, params,
)?),
Predicate::Pattern(pattern) => evaluate_pattern_predicate(storage, row, pattern, params),
Predicate::IsNull(expression) => Ok(evaluate_row_expression_with_local(
storage, row, expression, variable, value, params,
)? == Value::Null),
Predicate::IsNotNull(expression) => Ok(evaluate_row_expression_with_local(
storage, row, expression, variable, value, params,
)? != Value::Null),
Predicate::Exists(operand) => Ok(evaluate_row_operand_with_local(
storage, row, operand, variable, value, params,
)? != Value::Null),
Predicate::ExistsSubquery(matches) => {
let mut row = row.clone();
row.insert(variable.to_string(), Binding::Value(value.clone()));
evaluate_exists_subquery(storage, &row, matches, params)
}
Predicate::Boolean(expression) => {
match evaluate_row_expression_with_local(
storage, row, expression, variable, value, params,
)? {
Value::Boolean(value) => Ok(value),
Value::Null => Ok(false),
_ => Err(Error::Validation(
"list predicate bare operands must evaluate to boolean".to_string(),
)),
}
}
}
}
fn evaluate_row_operand_with_local(
storage: &dyn StorageInterface,
row: &Row,
operand: &Operand,
variable: &str,
value: &Value,
params: &Params,
) -> Result<Value> {
match operand {
Operand::Variable(name) if name == variable => Ok(value.clone()),
_ => evaluate_operand(storage, row, operand, params),
}
}
fn evaluate_predicate_with_local(
predicate: &Predicate,
variable: &str,
value: &Value,
params: &Params,
) -> Result<bool> {
match predicate {
Predicate::Comparison {
left,
operator,
right,
} => {
let left = evaluate_expression_with_local(left, variable, value, params)?;
let right = evaluate_expression_with_local(right, variable, value, params)?;
Ok(compare_values(&left, *operator, &right))
}
Predicate::In { item, list } => {
let item = evaluate_expression_with_local(item, variable, value, params)?;
let list_value = evaluate_expression_with_local(list, variable, value, params)?;
evaluate_in_predicate(list, &item, &list_value, None)
}
Predicate::StringMatch {
left,
operator,
right,
} => {
let left = evaluate_expression_with_local(left, variable, value, params)?;
let right = evaluate_expression_with_local(right, variable, value, params)?;
evaluate_string_predicate(&left, *operator, &right)
}
Predicate::And(left, right) => Ok(evaluate_predicate_with_local(
left, variable, value, params,
)? && evaluate_predicate_with_local(
right, variable, value, params,
)?),
Predicate::Or(left, right) => Ok(evaluate_predicate_with_local(
left, variable, value, params,
)? || evaluate_predicate_with_local(
right, variable, value, params,
)?),
Predicate::Xor(left, right) => Ok(evaluate_predicate_with_local(
left, variable, value, params,
)? ^ evaluate_predicate_with_local(
right, variable, value, params,
)?),
Predicate::Not(inner) => Ok(!evaluate_predicate_with_local(
inner, variable, value, params,
)?),
Predicate::Pattern(_) => Err(Error::UnsupportedQueryFeature(
"pattern predicates require a matched row context".to_string(),
)),
Predicate::IsNull(expression) => {
Ok(evaluate_expression_with_local(expression, variable, value, params)? == Value::Null)
}
Predicate::IsNotNull(expression) => {
Ok(evaluate_expression_with_local(expression, variable, value, params)? != Value::Null)
}
Predicate::Exists(operand) => {
Ok(evaluate_operand_with_local(operand, variable, value, params)? != Value::Null)
}
Predicate::ExistsSubquery(_) => Err(Error::UnsupportedQueryFeature(
"list predicates do not support EXISTS subqueries".to_string(),
)),
Predicate::Boolean(expression) => {
match evaluate_expression_with_local(expression, variable, value, params)? {
Value::Boolean(value) => Ok(value),
Value::Null => Ok(false),
_ => Err(Error::Validation(
"list predicate bare operands must evaluate to boolean".to_string(),
)),
}
}
}
}
fn evaluate_operand_with_local(
operand: &Operand,
variable: &str,
value: &Value,
params: &Params,
) -> Result<Value> {
match operand {
Operand::Variable(name) if name == variable => Ok(value.clone()),
Operand::Literal(value) => Ok(value.clone()),
Operand::Parameter(name) => params
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
_ => Err(Error::Validation(
"list predicate local expressions cannot reference graph variables here".to_string(),
)),
}
}
fn evaluate_operand(
storage: &dyn StorageInterface,
row: &Row,
operand: &Operand,
params: &Params,
) -> Result<Value> {
match operand {
Operand::Literal(value) => Ok(value.clone()),
Operand::Parameter(name) => params
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
Operand::Property { variable, key } => property_value(storage, row, variable, key),
Operand::DynamicProperty { variable, key } => {
let key = evaluate_row_expression(storage, row, key, params)?;
let Value::String(key) = key else {
return Err(Error::Validation(
"dynamic property keys must evaluate to strings".to_string(),
));
};
property_value(storage, row, variable, &key)
}
Operand::Variable(variable) => binding_value(storage, row, variable),
}
}
fn property_value(
storage: &dyn StorageInterface,
row: &Row,
variable: &str,
key: &str,
) -> Result<Value> {
if key == "__littlegraph_element_id" {
return row
.get(variable)
.ok_or_else(|| Error::Validation(format!("variable `{variable}` is not bound")))
.and_then(|binding| element_id_value(storage, binding));
}
match row.get(variable) {
Some(Binding::Null) => Ok(Value::Null),
Some(Binding::Node(node_id)) => Ok(storage_node(storage, *node_id)?
.properties
.get(key)
.cloned()
.unwrap_or(Value::Null)),
Some(Binding::Relationship(relationship_id)) => {
Ok(storage_relationship(storage, *relationship_id)?
.properties
.get(key)
.cloned()
.unwrap_or(Value::Null))
}
Some(Binding::Path(_)) => Ok(Value::Null),
Some(Binding::Value(_)) => Ok(Value::Null),
None => Err(Error::Validation(format!(
"variable `{variable}` is not bound"
))),
}
}
fn binding_value(storage: &dyn StorageInterface, row: &Row, variable: &str) -> Result<Value> {
match row.get(variable) {
Some(Binding::Null) => Ok(Value::Null),
Some(Binding::Node(node_id)) => Ok(node_value(storage_node(storage, *node_id)?)),
Some(Binding::Relationship(relationship_id)) => {
relationship_value(storage, storage_relationship(storage, *relationship_id)?)
}
Some(Binding::Path(path)) => path_value(storage, path),
Some(Binding::Value(value)) => Ok(value.clone()),
None => Err(Error::Validation(format!(
"variable `{variable}` is not bound"
))),
}
}
fn compare_values(left: &Value, operator: ComparisonOperator, right: &Value) -> bool {
match operator {
ComparisonOperator::Equal => {
left == right || numeric_ordering(left, right) == Some(Ordering::Equal)
}
ComparisonOperator::NotEqual => {
left != right && numeric_ordering(left, right) != Some(Ordering::Equal)
}
ComparisonOperator::LessThan => {
numeric_or_scalar_ordering(left, right) == Some(Ordering::Less)
}
ComparisonOperator::LessThanOrEqual => matches!(
numeric_or_scalar_ordering(left, right),
Some(Ordering::Less | Ordering::Equal)
),
ComparisonOperator::GreaterThan => {
numeric_or_scalar_ordering(left, right) == Some(Ordering::Greater)
}
ComparisonOperator::GreaterThanOrEqual => matches!(
numeric_or_scalar_ordering(left, right),
Some(Ordering::Greater | Ordering::Equal)
),
}
}
fn evaluate_in_predicate(
list_expression: &Expression,
item: &Value,
list: &Value,
storage: Option<&dyn StorageInterface>,
) -> Result<bool> {
let Value::List(values) = list else {
let detail = match list_expression {
Expression::Parameter(name) => format!("IN parameter `{name}` must be a list"),
_ => "IN right-hand side must be a list".to_string(),
};
return Err(Error::Validation(detail));
};
for chunk in values.chunks(QUERY_CONTROL_COMPARISON_BATCH) {
if let Some(storage) = storage {
storage.check_query_control()?;
}
if chunk.iter().any(|value| values_equal_for_in(item, value)) {
return Ok(true);
}
}
Ok(false)
}
fn values_equal_for_in(left: &Value, right: &Value) -> bool {
left == right || numeric_ordering(left, right) == Some(Ordering::Equal)
}
fn evaluate_string_predicate(
left: &Value,
operator: StringOperator,
right: &Value,
) -> Result<bool> {
let (Value::String(left), Value::String(right)) = (left, right) else {
return Ok(false);
};
Ok(match operator {
StringOperator::StartsWith => left.starts_with(right),
StringOperator::EndsWith => left.ends_with(right),
StringOperator::Contains => left.contains(right),
StringOperator::Regex => Regex::new(right)
.map_err(|error| Error::Validation(format!("invalid regex pattern: {error}")))?
.is_match(left),
})
}
fn numeric_or_scalar_ordering(left: &Value, right: &Value) -> Option<Ordering> {
numeric_ordering(left, right).or_else(|| match (left, right) {
(Value::String(left), Value::String(right)) => Some(left.cmp(right)),
(Value::Boolean(left), Value::Boolean(right)) => Some(left.cmp(right)),
_ => None,
})
}
fn numeric_ordering(left: &Value, right: &Value) -> Option<Ordering> {
match (left, right) {
(Value::Integer(left), Value::Integer(right)) => Some(left.cmp(right)),
(Value::Integer(left), Value::Float(right)) => (*left as f64).partial_cmp(right),
(Value::Float(left), Value::Integer(right)) => left.partial_cmp(&(*right as f64)),
(Value::Float(left), Value::Float(right)) => left.partial_cmp(right),
_ => None,
}
}
fn apply_distinct(
storage: &dyn StorageInterface,
rows: &mut Vec<Record>,
distinct: bool,
) -> Result<()> {
if !distinct {
return Ok(());
}
let mut seen = Vec::<Vec<Value>>::new();
let mut distinct_rows = Vec::with_capacity(rows.len());
for row in rows.drain(..) {
storage.check_query_control()?;
if controlled_position(storage, &seen, |values| values == &row.values)?.is_none() {
seen.push(row.values.clone());
distinct_rows.push(row);
}
}
*rows = distinct_rows;
Ok(())
}
fn apply_order_by(
rows: &mut [Record],
columns: &[String],
returns: &[ReturnItem],
order_by: &[OrderItem],
) -> Result<()> {
let order_columns = order_by
.iter()
.map(|order_item| {
let index = order_column_index(&order_item.item, returns)?;
columns.get(index).ok_or_else(|| {
Error::Execution(format!(
"ORDER BY item `{}` was not projected",
expression_column(&order_item.item)
))
})?;
Ok((index, order_item.direction))
})
.collect::<Result<Vec<_>>>()?;
rows.sort_by(|left, right| compare_records(left, right, &order_columns));
Ok(())
}
fn compare_records(
left: &Record,
right: &Record,
order_columns: &[(usize, OrderDirection)],
) -> Ordering {
for (index, direction) in order_columns {
let ordering = compare_sort_values(&left.values[*index], &right.values[*index]);
let ordering = match direction {
OrderDirection::Ascending => ordering,
OrderDirection::Descending => ordering.reverse(),
};
if ordering != Ordering::Equal {
return ordering;
}
}
Ordering::Equal
}
fn compare_sort_values(left: &Value, right: &Value) -> Ordering {
match (left, right) {
(Value::Null, Value::Null) => Ordering::Equal,
(Value::Null, _) => Ordering::Less,
(_, Value::Null) => Ordering::Greater,
_ => numeric_or_scalar_ordering(left, right)
.unwrap_or_else(|| value_sort_key(left).cmp(&value_sort_key(right))),
}
}
fn value_sort_key(value: &Value) -> (u8, String) {
let rank = match value {
Value::Null => 0,
Value::Boolean(_) => 1,
Value::Integer(_) | Value::Float(_) => 2,
Value::String(_) => 3,
Value::List(_) => 4,
Value::Map(_) => 5,
Value::Node(_) => 6,
Value::Relationship(_) => 7,
Value::Path(_) => 8,
};
(rank, format!("{value:?}"))
}
fn apply_limit(
storage: &dyn StorageInterface,
rows: &mut Vec<Record>,
limit: Option<&RowCount>,
params: &Params,
) -> Result<()> {
let Some(limit) = limit else {
return Ok(());
};
let limit = resolve_row_count(storage, "LIMIT", limit, params)?;
rows.truncate(limit);
Ok(())
}
fn apply_skip(
storage: &dyn StorageInterface,
rows: &mut Vec<Record>,
skip: Option<&RowCount>,
params: &Params,
) -> Result<()> {
let Some(skip) = skip else {
return Ok(());
};
let skip = resolve_row_count(storage, "SKIP", skip, params)?;
if skip >= rows.len() {
rows.clear();
} else {
rows.drain(0..skip);
}
Ok(())
}
fn resolve_row_count(
storage: &dyn StorageInterface,
name: &str,
row_count: &RowCount,
params: &Params,
) -> Result<usize> {
match row_count {
RowCount::Literal(value) => usize_row_count(name, *value),
RowCount::InvalidLiteral(value) => Err(Error::Validation(format!(
"{name} literal `{value}` must be a non-negative integer"
))),
RowCount::Parameter(parameter_name) => {
let value = params.get(parameter_name).ok_or_else(|| {
Error::Validation(format!("missing query parameter `{parameter_name}`"))
})?;
match value {
Value::Integer(value) => usize_row_count(name, *value),
_ => Err(Error::Validation(format!(
"{name} parameter `{parameter_name}` must be a non-negative integer"
))),
}
}
RowCount::Expression(expression) => {
match evaluate_row_expression(storage, &Row::new(), expression, params)? {
Value::Integer(value) => usize_row_count(name, value),
_ => Err(Error::Validation(format!(
"{name} expression must be a non-negative integer"
))),
}
}
}
}
fn usize_row_count(name: &str, value: i64) -> Result<usize> {
usize::try_from(value)
.map_err(|_| Error::Validation(format!("{name} must be a non-negative integer")))
}
fn bind_node(row: &mut Row, variable: Option<&String>, node_id: NodeId) -> Result<bool> {
let Some(variable) = variable else {
return Ok(true);
};
bind(row, variable, Binding::Node(node_id))
}
fn bind_relationship(
row: &mut Row,
variable: Option<&String>,
relationship_id: RelationshipId,
) -> Result<bool> {
let Some(variable) = variable else {
return Ok(true);
};
bind(row, variable, Binding::Relationship(relationship_id))
}
fn bind_path(storage: &dyn StorageInterface, row: &mut Row, pattern: &Pattern) -> Result<()> {
let Some(variable) = &pattern.variable else {
return Ok(());
};
let mut nodes = Vec::new();
let mut relationships = Vec::new();
let start_variable = pattern.start.variable.as_ref().ok_or_else(|| {
Error::UnsupportedQueryFeature(
"path binding requires the start node to have a variable".to_string(),
)
})?;
nodes.push(bound_node(row, start_variable)?);
for (chain_index, chain) in pattern.chains.iter().enumerate() {
if chain.relationship.variable_length {
let segment_variable = variable_length_path_segment_variable(chain_index);
let Some(Binding::Path(segment)) = row.get(&segment_variable) else {
return Err(Error::Execution(
"variable-length path segment is not bound".to_string(),
));
};
controlled_extend_from_slice(storage, &mut relationships, &segment.relationships)?;
controlled_extend_from_slice(
storage,
&mut nodes,
segment.nodes.get(1..).unwrap_or_default(),
)?;
continue;
}
let relationship_variable = chain.relationship.variable.as_ref().ok_or_else(|| {
Error::UnsupportedQueryFeature(
"path binding currently requires relationships to have variables".to_string(),
)
})?;
relationships.push(bound_relationship(row, relationship_variable)?);
let node_variable = chain.node.variable.as_ref().ok_or_else(|| {
Error::UnsupportedQueryFeature(
"path binding requires path nodes to have variables".to_string(),
)
})?;
nodes.push(bound_node(row, node_variable)?);
}
bind(
row,
variable,
Binding::Path(PathBinding {
nodes,
relationships,
}),
)?;
Ok(())
}
fn variable_length_path_segment_variable(index: usize) -> String {
format!("__littlegraph_anon_path_segment_{index}")
}
fn bind(row: &mut Row, variable: &str, binding: Binding) -> Result<bool> {
match row.get(variable) {
Some(existing) if existing == &binding => Ok(true),
Some(Binding::Null) => Ok(false),
Some(Binding::Node(_))
| Some(Binding::Relationship(_))
| Some(Binding::Path(_))
| Some(Binding::Value(_)) => Ok(false),
None => {
row.insert(variable.to_string(), binding);
Ok(true)
}
}
}
fn bound_node(row: &Row, variable: &str) -> Result<NodeId> {
match row.get(variable) {
Some(Binding::Node(node_id)) => Ok(*node_id),
Some(Binding::Null) => Err(Error::Execution(format!(
"variable `{variable}` is bound to null, not a node"
))),
Some(Binding::Relationship(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a relationship, not a node"
))),
Some(Binding::Path(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a path, not a node"
))),
Some(Binding::Value(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a value, not a node"
))),
None => Err(Error::Execution(format!(
"variable `{variable}` is not bound in the current row"
))),
}
}
fn bound_relationship(row: &Row, variable: &str) -> Result<RelationshipId> {
match row.get(variable) {
Some(Binding::Relationship(relationship_id)) => Ok(*relationship_id),
Some(Binding::Null) => Err(Error::Execution(format!(
"variable `{variable}` is bound to null, not a relationship"
))),
Some(Binding::Node(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a node, not a relationship"
))),
Some(Binding::Path(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a path, not a relationship"
))),
Some(Binding::Value(_)) => Err(Error::Execution(format!(
"variable `{variable}` is bound to a value, not a relationship"
))),
None => Err(Error::Execution(format!(
"variable `{variable}` is not bound in the current row"
))),
}
}
fn null_row(bound_variables: &[String]) -> Row {
bound_variables
.iter()
.map(|variable| (variable.clone(), Binding::Null))
.collect()
}
fn pattern_bound_variables(pattern: &Pattern) -> Result<Vec<String>> {
let mut variables = Vec::new();
push_unique_variable(&mut variables, pattern.start.variable.as_ref());
for chain in &pattern.chains {
if !chain.relationship.variable_length {
push_unique_variable(&mut variables, chain.relationship.variable.as_ref());
}
push_unique_variable(&mut variables, chain.node.variable.as_ref());
}
Ok(variables)
}
fn push_unique_variable(variables: &mut Vec<String>, variable: Option<&String>) {
if let Some(variable) = variable {
if variable.starts_with("__littlegraph_anon_") {
return;
}
if !variables.iter().any(|existing| existing == variable) {
variables.push(variable.clone());
}
}
}
fn project_row(
storage: &dyn StorageInterface,
row: &Row,
returns: &[ReturnItem],
params: &Params,
) -> Result<Record> {
storage.check_query_control()?;
returns
.iter()
.map(|item| project_item(storage, row, item, params))
.collect::<Result<Vec<_>>>()
.map(|values| Record { values })
}
fn return_items_include_aggregate(returns: &[ReturnItem]) -> bool {
returns
.iter()
.any(|item| return_expression_is_aggregate(&item.expression))
}
fn return_expression_is_aggregate(expression: &ReturnExpression) -> bool {
return_expression_is_count(expression)
|| matches!(
expression,
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 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(_)
)
}
#[derive(Debug)]
struct AggregateGroup {
key_values: Vec<Value>,
rows: Vec<Row>,
}
#[derive(Debug)]
struct AggregateProjection {
record: Record,
order_values: Vec<Value>,
}
fn project_aggregate_rows(
storage: &dyn StorageInterface,
rows: &[Row],
returns: &[ReturnItem],
order_by: &[OrderItem],
params: &Params,
) -> Result<Vec<Record>> {
let group_items = returns
.iter()
.filter(|item| !return_expression_is_aggregate(&item.expression))
.collect::<Vec<_>>();
let groups = aggregate_groups(storage, rows, &group_items, params)?;
let mut projections = groups
.iter()
.map(|group| aggregate_projection(storage, group, returns, order_by, params))
.collect::<Result<Vec<_>>>()?;
sort_aggregate_projections(storage, &mut projections, order_by)?;
Ok(projections
.into_iter()
.map(|projection| projection.record)
.collect())
}
fn aggregate_groups(
storage: &dyn StorageInterface,
rows: &[Row],
group_items: &[&ReturnItem],
params: &Params,
) -> Result<Vec<AggregateGroup>> {
if group_items.is_empty() {
let mut group_rows = Vec::with_capacity(rows.len());
controlled_extend_from_slice(storage, &mut group_rows, rows)?;
return Ok(vec![AggregateGroup {
key_values: Vec::new(),
rows: group_rows,
}]);
}
let mut groups = Vec::<AggregateGroup>::new();
for row in rows {
storage.check_query_control()?;
let key_values = group_items
.iter()
.map(|item| project_item(storage, row, item, params))
.collect::<Result<Vec<_>>>()?;
if let Some(index) =
controlled_position(storage, &groups, |group| group.key_values == key_values)?
{
groups[index].rows.push(row.clone());
} else {
groups.push(AggregateGroup {
key_values,
rows: vec![row.clone()],
});
}
}
Ok(groups)
}
fn aggregate_projection(
storage: &dyn StorageInterface,
group: &AggregateGroup,
returns: &[ReturnItem],
order_by: &[OrderItem],
params: &Params,
) -> Result<AggregateProjection> {
let mut key_index = 0;
let values = returns
.iter()
.map(|item| {
if return_expression_is_aggregate(&item.expression) {
aggregate_value(storage, &group.rows, &item.expression, params)
} else {
let value = group.key_values.get(key_index).cloned().ok_or_else(|| {
Error::Execution("aggregate group key is missing".to_string())
})?;
key_index += 1;
Ok(value)
}
})
.collect::<Result<Vec<_>>>()?;
let record = Record { values };
let order_values = order_by
.iter()
.map(|order_item| {
aggregate_order_value(storage, group, returns, &record, order_item, params)
})
.collect::<Result<Vec<_>>>()?;
Ok(AggregateProjection {
record,
order_values,
})
}
fn aggregate_order_value(
storage: &dyn StorageInterface,
group: &AggregateGroup,
returns: &[ReturnItem],
record: &Record,
order_item: &OrderItem,
params: &Params,
) -> Result<Value> {
if let Some(index) = aggregate_order_column_index(&order_item.item, returns) {
return record.values.get(index).cloned().ok_or_else(|| {
Error::Execution(format!(
"ORDER BY item `{}` was not projected",
expression_column(&order_item.item)
))
});
}
aggregate_value(storage, &group.rows, &order_item.item.expression, params)
}
fn aggregate_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &ReturnExpression,
params: &Params,
) -> Result<Value> {
if return_expression_is_count(expression) {
return count_value(storage, rows, expression, params).map(Value::Integer);
}
match expression {
ReturnExpression::SumProperty { variable, key } => {
sum_property_value(storage, rows, variable, key)
}
ReturnExpression::AvgProperty { variable, key } => {
avg_property_value(storage, rows, variable, key)
}
ReturnExpression::MinProperty { variable, key } => {
min_max_property_value(storage, rows, variable, key, MinMax::Min)
}
ReturnExpression::MaxProperty { variable, key } => {
min_max_property_value(storage, rows, variable, key, MinMax::Max)
}
ReturnExpression::SumExpression(expression) => {
sum_expression_value(storage, rows, expression, params)
}
ReturnExpression::AvgExpression(expression) => {
avg_expression_value(storage, rows, expression, params)
}
ReturnExpression::SumDistinctExpression(expression) => {
sum_distinct_expression_value(storage, rows, expression, params)
}
ReturnExpression::AvgDistinctExpression(expression) => {
avg_distinct_expression_value(storage, rows, expression, params)
}
ReturnExpression::MinExpression(expression) => {
min_max_expression_value(storage, rows, expression, params, MinMax::Min)
}
ReturnExpression::MaxExpression(expression) => {
min_max_expression_value(storage, rows, expression, params, MinMax::Max)
}
ReturnExpression::MinDistinctExpression(expression) => {
min_max_expression_value(storage, rows, expression, params, MinMax::Min)
}
ReturnExpression::MaxDistinctExpression(expression) => {
min_max_expression_value(storage, rows, expression, params, MinMax::Max)
}
ReturnExpression::CollectVariable(variable) => {
collect_variable_value(storage, rows, variable)
}
ReturnExpression::CollectProperty { variable, key } => {
collect_property_value(storage, rows, variable, key)
}
ReturnExpression::CollectDistinctVariable(variable) => {
collect_distinct_variable_value(storage, rows, variable)
}
ReturnExpression::CollectDistinctProperty { variable, key } => {
collect_distinct_property_value(storage, rows, variable, key)
}
ReturnExpression::CollectExpression(expression) => {
collect_expression_value(storage, rows, expression, params)
}
ReturnExpression::CollectDistinctExpression(expression) => {
collect_distinct_expression_value(storage, rows, expression, params)
}
_ => Err(Error::Execution(
"non-aggregate expression passed to aggregate evaluation".to_string(),
)),
}
}
fn aggregate_order_column_index(item: &ReturnItem, returns: &[ReturnItem]) -> Option<usize> {
returns.iter().position(|return_item| {
return_expression_matches(return_item, item)
|| matches!(&item.expression, ReturnExpression::Variable(variable) if return_item.alias.as_deref() == Some(variable.as_str()))
})
}
fn sort_aggregate_projections(
storage: &dyn StorageInterface,
projections: &mut [AggregateProjection],
order_by: &[OrderItem],
) -> Result<()> {
controlled_sort_by(storage, projections, |left, right| {
for (index, order_item) in order_by.iter().enumerate() {
let ordering =
compare_sort_values(&left.order_values[index], &right.order_values[index]);
let ordering = match order_item.direction {
OrderDirection::Ascending => ordering,
OrderDirection::Descending => ordering.reverse(),
};
if ordering != Ordering::Equal {
return ordering;
}
}
Ordering::Equal
})
}
fn count_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &ReturnExpression,
params: &Params,
) -> Result<i64> {
let count = match expression {
ReturnExpression::CountStar => rows.len(),
ReturnExpression::CountDistinctStar => {
let mut seen = Vec::<Row>::new();
for row in rows {
storage.check_query_control()?;
if controlled_position(storage, &seen, |existing| existing == row)?.is_none() {
seen.push(row.clone());
}
}
seen.len()
}
ReturnExpression::CountVariable(variable) => {
let mut count = 0;
for row in rows {
storage.check_query_control()?;
count +=
usize::from(matches!(row.get(variable), Some(binding) if !binding.is_null()));
}
count
}
ReturnExpression::CountDistinctVariable(variable) => {
let mut seen = Vec::<Value>::new();
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
if binding.is_null() {
continue;
}
let value = binding_value_from_binding(storage, binding)?;
if controlled_position(storage, &seen, |existing| existing == &value)?.is_none() {
seen.push(value);
}
}
seen.len()
}
ReturnExpression::CountProperty { variable, key } => {
count_property_values(storage, rows, variable, key)?
}
ReturnExpression::CountDistinctProperty { variable, key } => {
count_distinct_property_values(storage, rows, variable, key)?
}
ReturnExpression::CountExpression(expression) => {
count_expression_values(storage, rows, expression, params)?
}
ReturnExpression::CountDistinctExpression(expression) => {
count_distinct_expression_values(storage, rows, expression, params)?
}
ReturnExpression::Variable(_)
| ReturnExpression::Star
| ReturnExpression::Property { .. }
| ReturnExpression::PropertyWildcard(_)
| ReturnExpression::Scalar(_)
| ReturnExpression::Labels(_)
| ReturnExpression::Type(_)
| ReturnExpression::Properties(_)
| ReturnExpression::Keys(_)
| ReturnExpression::ElementId(_)
| ReturnExpression::Id(_)
| ReturnExpression::StartNode(_)
| ReturnExpression::EndNode(_)
| ReturnExpression::Nodes(_)
| ReturnExpression::Relationships(_)
| ReturnExpression::Length(_)
| 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(_) => {
return Err(Error::Execution(
"count record requested for non-count return item".to_string(),
))
}
};
i64::try_from(count).map_err(|_| Error::Execution("count result exceeds i64 range".to_string()))
}
fn count_property_values(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
key: &str,
) -> Result<usize> {
rows.iter().try_fold(0, |count, row| {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
return Ok(count);
};
let value = binding_property_value(storage, binding, key)?;
Ok(count + usize::from(value != Value::Null))
})
}
fn count_distinct_property_values(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
key: &str,
) -> Result<usize> {
let mut seen = Vec::new();
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
let value = binding_property_value(storage, binding, key)?;
if value != Value::Null
&& controlled_position(storage, &seen, |existing| existing == &value)?.is_none()
{
seen.push(value);
}
}
Ok(seen.len())
}
fn count_expression_values(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<usize> {
rows.iter().try_fold(0, |count, row| {
let value = evaluate_row_expression(storage, row, expression, params)?;
Ok(count + usize::from(value != Value::Null))
})
}
fn count_distinct_expression_values(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<usize> {
let mut seen = Vec::new();
for row in rows {
let value = evaluate_row_expression(storage, row, expression, params)?;
if value != Value::Null
&& controlled_position(storage, &seen, |existing| existing == &value)?.is_none()
{
seen.push(value);
}
}
Ok(seen.len())
}
fn sum_property_value(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
key: &str,
) -> Result<Value> {
let mut integer_sum = 0_i64;
let mut float_sum = 0.0_f64;
let mut saw_float = false;
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
match binding_property_value(storage, binding, key)? {
Value::Null => {}
Value::Integer(value) if !saw_float => {
integer_sum = integer_sum.checked_add(value).ok_or_else(|| {
Error::Execution("sum integer result exceeds i64 range".to_string())
})?;
}
Value::Integer(value) => {
float_sum += value as f64;
}
Value::Float(value) => {
if !saw_float {
float_sum = integer_sum as f64;
saw_float = true;
}
float_sum += value;
}
_ => {
return Err(Error::Validation(
"sum() requires numeric property values".to_string(),
))
}
}
}
if saw_float {
Ok(Value::Float(float_sum))
} else {
Ok(Value::Integer(integer_sum))
}
}
fn sum_expression_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<Value> {
let mut integer_sum = 0_i64;
let mut float_sum = 0.0_f64;
let mut saw_float = false;
for row in rows {
match evaluate_row_expression(storage, row, expression, params)? {
Value::Null => {}
Value::Integer(value) if !saw_float => {
integer_sum = integer_sum.checked_add(value).ok_or_else(|| {
Error::Execution("sum integer result exceeds i64 range".to_string())
})?;
}
Value::Integer(value) => {
float_sum += value as f64;
}
Value::Float(value) => {
if !saw_float {
float_sum = integer_sum as f64;
saw_float = true;
}
float_sum += value;
}
_ => {
return Err(Error::Validation(
"sum() requires numeric values".to_string(),
))
}
}
}
if saw_float {
Ok(Value::Float(float_sum))
} else {
Ok(Value::Integer(integer_sum))
}
}
fn sum_distinct_expression_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<Value> {
let values = distinct_expression_values(storage, rows, expression, params)?;
let rows = values
.into_iter()
.map(|value| Row::from([("__value".to_string(), Binding::Value(value))]))
.collect::<Vec<_>>();
sum_expression_value(
storage,
&rows,
&Expression::Operand(Operand::Variable("__value".to_string())),
params,
)
}
fn avg_property_value(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
key: &str,
) -> Result<Value> {
let mut sum = 0.0_f64;
let mut count = 0_usize;
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
match binding_property_value(storage, binding, key)? {
Value::Null => {}
Value::Integer(value) => {
sum += value as f64;
count += 1;
}
Value::Float(value) => {
sum += value;
count += 1;
}
_ => {
return Err(Error::Validation(
"avg() requires numeric property values".to_string(),
))
}
}
}
if count == 0 {
Ok(Value::Null)
} else {
Ok(Value::Float(sum / count as f64))
}
}
fn avg_expression_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<Value> {
let mut sum = 0.0_f64;
let mut count = 0_usize;
for row in rows {
match evaluate_row_expression(storage, row, expression, params)? {
Value::Null => {}
Value::Integer(value) => {
sum += value as f64;
count += 1;
}
Value::Float(value) => {
sum += value;
count += 1;
}
_ => {
return Err(Error::Validation(
"avg() requires numeric values".to_string(),
))
}
}
}
if count == 0 {
Ok(Value::Null)
} else {
Ok(Value::Float(sum / count as f64))
}
}
fn avg_distinct_expression_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<Value> {
let values = distinct_expression_values(storage, rows, expression, params)?;
let rows = values
.into_iter()
.map(|value| Row::from([("__value".to_string(), Binding::Value(value))]))
.collect::<Vec<_>>();
avg_expression_value(
storage,
&rows,
&Expression::Operand(Operand::Variable("__value".to_string())),
params,
)
}
fn distinct_expression_values(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<Vec<Value>> {
let mut values = Vec::new();
for row in rows {
let value = evaluate_row_expression(storage, row, expression, params)?;
if value != Value::Null
&& controlled_position(storage, &values, |existing| existing == &value)?.is_none()
{
values.push(value);
}
}
Ok(values)
}
#[derive(Clone, Copy)]
enum MinMax {
Min,
Max,
}
fn min_max_property_value(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
key: &str,
mode: MinMax,
) -> Result<Value> {
let mut selected = None::<Value>;
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
let value = binding_property_value(storage, binding, key)?;
if value == Value::Null {
continue;
}
match &selected {
None => selected = Some(value),
Some(current) => {
let ordering = compare_sort_values(&value, current);
let replace = match mode {
MinMax::Min => ordering == Ordering::Less,
MinMax::Max => ordering == Ordering::Greater,
};
if replace {
selected = Some(value);
}
}
}
}
Ok(selected.unwrap_or(Value::Null))
}
fn min_max_expression_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
mode: MinMax,
) -> Result<Value> {
let mut selected = None::<Value>;
for row in rows {
let value = evaluate_row_expression(storage, row, expression, params)?;
if value == Value::Null {
continue;
}
match &selected {
None => selected = Some(value),
Some(current) => {
let ordering = compare_sort_values(&value, current);
let replace = match mode {
MinMax::Min => ordering == Ordering::Less,
MinMax::Max => ordering == Ordering::Greater,
};
if replace {
selected = Some(value);
}
}
}
}
Ok(selected.unwrap_or(Value::Null))
}
fn collect_property_value(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
key: &str,
) -> Result<Value> {
let mut values = Vec::new();
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
let value = binding_property_value(storage, binding, key)?;
if value != Value::Null {
values.push(value);
}
}
Ok(Value::List(values))
}
fn collect_variable_value(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
) -> Result<Value> {
let mut values = Vec::new();
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
if !binding.is_null() {
values.push(binding_value_from_binding(storage, binding)?);
}
}
Ok(Value::List(values))
}
fn collect_distinct_variable_value(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
) -> Result<Value> {
let mut values = Vec::new();
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
if binding.is_null() {
continue;
}
let value = binding_value_from_binding(storage, binding)?;
if controlled_position(storage, &values, |existing| existing == &value)?.is_none() {
values.push(value);
}
}
Ok(Value::List(values))
}
fn collect_expression_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<Value> {
rows.iter()
.map(|row| evaluate_row_expression(storage, row, expression, params))
.filter(|value| !matches!(value, Ok(Value::Null)))
.collect::<Result<Vec<_>>>()
.map(Value::List)
}
fn collect_distinct_expression_value(
storage: &dyn StorageInterface,
rows: &[Row],
expression: &Expression,
params: &Params,
) -> Result<Value> {
let mut values = Vec::new();
for row in rows {
let value = evaluate_row_expression(storage, row, expression, params)?;
if value != Value::Null
&& controlled_position(storage, &values, |existing| existing == &value)?.is_none()
{
values.push(value);
}
}
Ok(Value::List(values))
}
fn collect_distinct_property_value(
storage: &dyn StorageInterface,
rows: &[Row],
variable: &str,
key: &str,
) -> Result<Value> {
let mut values = Vec::new();
for row in rows {
storage.check_query_control()?;
let Some(binding) = row.get(variable) else {
continue;
};
let value = binding_property_value(storage, binding, key)?;
if value != Value::Null
&& controlled_position(storage, &values, |existing| existing == &value)?.is_none()
{
values.push(value);
}
}
Ok(Value::List(values))
}
fn project_item(
storage: &dyn StorageInterface,
row: &Row,
item: &ReturnItem,
params: &Params,
) -> Result<Value> {
match &item.expression {
ReturnExpression::Star => Err(Error::Execution(
"RETURN * should be expanded before execution".to_string(),
)),
ReturnExpression::Variable(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
binding_entity_value(storage, binding)
}
ReturnExpression::Property { variable, key } => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
binding_property_value(storage, binding, key)
}
ReturnExpression::PropertyWildcard(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
properties_value(storage, binding)
}
ReturnExpression::Scalar(expression) => {
evaluate_row_expression(storage, row, expression, params)
}
ReturnExpression::Labels(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
labels_value(storage, binding)
}
ReturnExpression::Type(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
relationship_type_value(storage, binding)
}
ReturnExpression::Properties(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
properties_value(storage, binding)
}
ReturnExpression::Keys(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
keys_value(storage, binding)
}
ReturnExpression::ElementId(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
element_id_value(storage, binding)
}
ReturnExpression::Id(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
id_value(binding)
}
ReturnExpression::StartNode(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
relationship_endpoint_value(storage, binding, RelationshipEndpoint::Start)
}
ReturnExpression::EndNode(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
relationship_endpoint_value(storage, binding, RelationshipEndpoint::End)
}
ReturnExpression::Nodes(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
path_nodes_value(storage, binding)
}
ReturnExpression::Relationships(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
path_relationships_value(storage, binding)
}
ReturnExpression::Length(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"RETURN variable `{variable}` is not bound in the current row"
))
})?;
path_length_value(binding)
}
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(_) => Err(Error::Execution(
"aggregate return item cannot be projected per row".to_string(),
)),
}
}
fn labels_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
if binding.is_null() {
return Ok(Value::Null);
}
let Binding::Node(node_id) = binding else {
return Err(Error::Validation(
"labels() requires a node variable".to_string(),
));
};
let node = storage_node(storage, *node_id)?;
Ok(Value::List(
node.labels.iter().cloned().map(Value::String).collect(),
))
}
fn relationship_type_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
if binding.is_null() {
return Ok(Value::Null);
}
let Binding::Relationship(relationship_id) = binding else {
return Err(Error::Validation(
"type() requires a relationship variable".to_string(),
));
};
let relationship = storage_relationship(storage, *relationship_id)?;
Ok(Value::String(relationship.r#type.clone()))
}
fn properties_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
match binding {
Binding::Null => Ok(Value::Null),
Binding::Node(node_id) => Ok(Value::Map(
storage_node(storage, *node_id)?.properties.clone(),
)),
Binding::Relationship(relationship_id) => Ok(Value::Map(
storage_relationship(storage, *relationship_id)?
.properties
.clone(),
)),
Binding::Path(_) => Err(Error::Validation(
"properties() requires a node or relationship variable".to_string(),
)),
Binding::Value(_) => Err(Error::Validation(
"properties() requires a node or relationship variable".to_string(),
)),
}
}
fn evaluate_map_projection_value(
storage: &dyn StorageInterface,
row: &Row,
variable: &str,
items: &[crate::cypher::ast::MapProjectionItem],
params: &Params,
) -> Result<Value> {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"map projection variable `{variable}` is not bound in the current row"
))
})?;
if binding.is_null() {
return Ok(Value::Null);
}
let mut values = BTreeMap::new();
for item in items {
match item {
crate::cypher::ast::MapProjectionItem::AllProperties => {
values.extend(binding_properties(storage, binding)?);
}
crate::cypher::ast::MapProjectionItem::Property(key) => {
values.insert(key.clone(), binding_property_value(storage, binding, key)?);
}
crate::cypher::ast::MapProjectionItem::Variable(variable) => {
let binding = row.get(variable).ok_or_else(|| {
Error::Execution(format!(
"map projection variable selector `{variable}` is not bound in the current row"
))
})?;
values.insert(variable.clone(), binding_entity_value(storage, binding)?);
}
crate::cypher::ast::MapProjectionItem::Expression { key, expression } => {
values.insert(
key.clone(),
evaluate_row_expression(storage, row, expression, params)?,
);
}
}
}
Ok(Value::Map(values))
}
fn binding_properties(
storage: &dyn StorageInterface,
binding: &Binding,
) -> Result<BTreeMap<String, Value>> {
match binding {
Binding::Null => Ok(BTreeMap::new()),
Binding::Node(node_id) => Ok(storage_node(storage, *node_id)?.properties.clone()),
Binding::Relationship(relationship_id) => {
Ok(storage_relationship(storage, *relationship_id)?
.properties
.clone())
}
Binding::Path(_) => Err(Error::Validation(
"map projection requires a node or relationship variable".to_string(),
)),
Binding::Value(_) => Err(Error::Validation(
"map projection requires a node or relationship variable".to_string(),
)),
}
}
fn keys_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
let properties = match binding {
Binding::Null => return Ok(Value::Null),
Binding::Node(node_id) => &storage_node(storage, *node_id)?.properties,
Binding::Relationship(relationship_id) => {
&storage_relationship(storage, *relationship_id)?.properties
}
Binding::Path(_) => {
return Err(Error::Validation(
"keys() requires a node or relationship variable".to_string(),
))
}
Binding::Value(_) => {
return Err(Error::Validation(
"keys() requires a node or relationship variable".to_string(),
))
}
};
Ok(Value::List(
properties.keys().cloned().map(Value::String).collect(),
))
}
fn element_id_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
match binding {
Binding::Null => Ok(Value::Null),
Binding::Node(node_id) => Ok(Value::String(
storage_node(storage, *node_id)?.external_id.clone(),
)),
Binding::Relationship(relationship_id) => Ok(Value::String(
storage_relationship(storage, *relationship_id)?
.external_id
.clone(),
)),
Binding::Path(_) => Err(Error::Validation(
"elementId() requires a node or relationship variable".to_string(),
)),
Binding::Value(_) => Err(Error::Validation(
"elementId() requires a node or relationship variable".to_string(),
)),
}
}
fn id_value(binding: &Binding) -> Result<Value> {
match binding {
Binding::Null => Ok(Value::Null),
Binding::Node(node_id) => Ok(Value::Integer(*node_id as i64)),
Binding::Relationship(relationship_id) => Ok(Value::Integer(*relationship_id as i64)),
Binding::Path(_) => Err(Error::Validation(
"id() requires a node or relationship variable".to_string(),
)),
Binding::Value(_) => Err(Error::Validation(
"id() requires a node or relationship variable".to_string(),
)),
}
}
#[derive(Clone, Copy)]
enum RelationshipEndpoint {
Start,
End,
}
fn relationship_endpoint_value(
storage: &dyn StorageInterface,
binding: &Binding,
endpoint: RelationshipEndpoint,
) -> Result<Value> {
if binding.is_null() {
return Ok(Value::Null);
}
let Binding::Relationship(relationship_id) = binding else {
return Err(Error::Validation(
"startNode()/endNode() requires a relationship variable".to_string(),
));
};
let relationship = storage_relationship(storage, *relationship_id)?;
let node_id = match endpoint {
RelationshipEndpoint::Start => relationship.start,
RelationshipEndpoint::End => relationship.end,
};
Ok(node_value(storage_node(storage, node_id)?))
}
fn path_nodes_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
let Binding::Path(path) = binding else {
return Err(Error::Validation(
"nodes() requires a path variable".to_string(),
));
};
path.nodes
.iter()
.map(|node_id| Ok(node_value(storage_node(storage, *node_id)?)))
.collect::<Result<Vec<_>>>()
.map(Value::List)
}
fn path_relationships_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
let Binding::Path(path) = binding else {
return Err(Error::Validation(
"relationships() requires a path variable".to_string(),
));
};
path.relationships
.iter()
.map(|relationship_id| {
relationship_value(storage, storage_relationship(storage, *relationship_id)?)
})
.collect::<Result<Vec<_>>>()
.map(Value::List)
}
fn path_length_value(binding: &Binding) -> Result<Value> {
let Binding::Path(path) = binding else {
return Err(Error::Validation(
"length() requires a path variable".to_string(),
));
};
Ok(Value::Integer(path.relationships.len() as i64))
}
fn binding_entity_value(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
match binding {
Binding::Null => Ok(Value::Null),
Binding::Node(node_id) => Ok(node_value(storage_node(storage, *node_id)?)),
Binding::Relationship(relationship_id) => {
relationship_value(storage, storage_relationship(storage, *relationship_id)?)
}
Binding::Path(path) => path_value(storage, path),
Binding::Value(value) => Ok(value.clone()),
}
}
fn binding_property_value(
storage: &dyn StorageInterface,
binding: &Binding,
property: &str,
) -> Result<Value> {
match binding {
Binding::Null => Ok(Value::Null),
Binding::Node(node_id) => {
let node = storage_node(storage, *node_id)?;
Ok(node
.properties
.get(property)
.cloned()
.unwrap_or(Value::Null))
}
Binding::Relationship(relationship_id) => {
let relationship = storage_relationship(storage, *relationship_id)?;
Ok(relationship
.properties
.get(property)
.cloned()
.unwrap_or(Value::Null))
}
Binding::Path(_) => Ok(Value::Null),
Binding::Value(_) => Ok(Value::Null),
}
}
fn binding_value_from_binding(storage: &dyn StorageInterface, binding: &Binding) -> Result<Value> {
match binding {
Binding::Null => Ok(Value::Null),
Binding::Node(node_id) => Ok(node_value(storage_node(storage, *node_id)?)),
Binding::Relationship(relationship_id) => {
relationship_value(storage, storage_relationship(storage, *relationship_id)?)
}
Binding::Path(path) => path_value(storage, path),
Binding::Value(value) => Ok(value.clone()),
}
}
fn return_column(item: &ReturnItem) -> String {
item.alias
.as_ref()
.map_or_else(|| expression_column(item), Clone::clone)
}
fn expression_column(item: &ReturnItem) -> String {
return_expression_column(&item.expression)
}
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: &Expression) -> String {
match expression {
Expression::Literal(value) => scalar_literal_column(value),
Expression::Parameter(name) => format!("${name}"),
Expression::Operand(operand) => operand_column(operand),
Expression::Add(left, right) => {
format!(
"{} + {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
Expression::Subtract(left, right) => {
format!(
"{} - {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
Expression::Multiply(left, right) => {
format!(
"{} * {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
Expression::Divide(left, right) => {
format!(
"{} / {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
Expression::Modulo(left, right) => {
format!(
"{} % {}",
scalar_expression_column(left),
scalar_expression_column(right)
)
}
Expression::List(items) => {
let items = items
.iter()
.map(scalar_expression_column)
.collect::<Vec<_>>()
.join(", ");
format!("[{items}]")
}
Expression::Map(entries) => {
let entries = entries
.iter()
.map(|(key, value)| format!("{key}: {}", scalar_expression_column(value)))
.collect::<Vec<_>>()
.join(", ");
format!("{{{entries}}}")
}
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} }}")
}
Expression::PatternComprehension { projection, .. } => {
format!("[pattern | {}]", scalar_expression_column(projection))
}
Expression::Coalesce(items) => {
let items = items
.iter()
.map(scalar_expression_column)
.collect::<Vec<_>>()
.join(", ");
format!("coalesce({items})")
}
Expression::ToLower(expression) => {
format!("toLower({})", scalar_expression_column(expression))
}
Expression::ToUpper(expression) => {
format!("toUpper({})", scalar_expression_column(expression))
}
Expression::ToString(expression) => {
format!("toString({})", scalar_expression_column(expression))
}
Expression::ToInteger(expression) => {
format!("toInteger({})", scalar_expression_column(expression))
}
Expression::ToFloat(expression) => {
format!("toFloat({})", scalar_expression_column(expression))
}
Expression::ToBoolean(expression) => {
format!("toBoolean({})", scalar_expression_column(expression))
}
Expression::ToStringOrNull(expression) => {
format!("toStringOrNull({})", scalar_expression_column(expression))
}
Expression::ToIntegerOrNull(expression) => {
format!("toIntegerOrNull({})", scalar_expression_column(expression))
}
Expression::ToFloatOrNull(expression) => {
format!("toFloatOrNull({})", scalar_expression_column(expression))
}
Expression::ToBooleanOrNull(expression) => {
format!("toBooleanOrNull({})", scalar_expression_column(expression))
}
Expression::IsEmpty(expression) => {
format!("isEmpty({})", scalar_expression_column(expression))
}
Expression::Head(expression) => format!("head({})", scalar_expression_column(expression)),
Expression::Last(expression) => format!("last({})", scalar_expression_column(expression)),
Expression::Tail(expression) => format!("tail({})", scalar_expression_column(expression)),
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})"),
}
}
Expression::ListIndex { value, index } => {
format!(
"{}[{}]",
scalar_expression_column(value),
scalar_expression_column(index)
)
}
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))
}
Expression::Size(expression) => format!("size({})", scalar_expression_column(expression)),
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(", "))
}
Expression::Replace {
value,
search,
replacement,
} => format!(
"replace({}, {}, {})",
scalar_expression_column(value),
scalar_expression_column(search),
scalar_expression_column(replacement)
),
Expression::Trim { mode, expression } => {
let function = match mode {
TrimMode::Both => "trim",
TrimMode::Left => "lTrim",
TrimMode::Right => "rTrim",
};
format!("{function}({})", scalar_expression_column(expression))
}
Expression::Split { value, delimiter } => format!(
"split({}, {})",
scalar_expression_column(value),
scalar_expression_column(delimiter)
),
Expression::StringSlice {
mode,
value,
length,
} => {
let function = match mode {
StringSliceMode::Left => "left",
StringSliceMode::Right => "right",
};
format!(
"{function}({}, {})",
scalar_expression_column(value),
scalar_expression_column(length)
)
}
Expression::Reverse(expression) => {
format!("reverse({})", scalar_expression_column(expression))
}
Expression::Abs(expression) => format!("abs({})", scalar_expression_column(expression)),
Expression::Rounding { mode, expression } => {
let function = match mode {
RoundingMode::Ceil => "ceil",
RoundingMode::Floor => "floor",
};
format!("{function}({})", scalar_expression_column(expression))
}
Expression::Sign(expression) => format!("sign({})", scalar_expression_column(expression)),
Expression::Sqrt(expression) => format!("sqrt({})", scalar_expression_column(expression)),
Expression::Round(expression) => format!("round({})", scalar_expression_column(expression)),
Expression::Log(expression) => format!("log({})", scalar_expression_column(expression)),
Expression::Log10(expression) => format!("log10({})", scalar_expression_column(expression)),
Expression::Exp(expression) => format!("exp({})", scalar_expression_column(expression)),
Expression::AngleConversion { mode, expression } => {
let function = match mode {
AngleConversionMode::Degrees => "degrees",
AngleConversionMode::Radians => "radians",
};
format!("{function}({})", scalar_expression_column(expression))
}
Expression::Trigonometric { mode, expression } => {
let function = match mode {
TrigonometricMode::Sin => "sin",
TrigonometricMode::Cos => "cos",
TrigonometricMode::Tan => "tan",
TrigonometricMode::Cot => "cot",
};
format!("{function}({})", scalar_expression_column(expression))
}
Expression::InverseTrigonometric { mode, expression } => {
let function = match mode {
InverseTrigonometricMode::Acos => "acos",
InverseTrigonometricMode::Asin => "asin",
InverseTrigonometricMode::Atan => "atan",
};
format!("{function}({})", scalar_expression_column(expression))
}
Expression::Atan2 { y, x } => format!(
"atan2({}, {})",
scalar_expression_column(y),
scalar_expression_column(x)
),
Expression::Haversin(expression) => {
format!("haversin({})", scalar_expression_column(expression))
}
Expression::ListPredicate {
mode,
variable,
list,
..
} => {
let function = match mode {
ListPredicateMode::All => "all",
ListPredicateMode::Any => "any",
ListPredicateMode::None => "none",
ListPredicateMode::Single => "single",
};
format!(
"{function}({variable} IN {} WHERE predicate)",
scalar_expression_column(list)
)
}
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)
)
}
Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => format!(
"reduce({accumulator} = {}, {variable} IN {} | {})",
scalar_expression_column(initial),
scalar_expression_column(list),
scalar_expression_column(expression)
),
Expression::Pi => "pi()".to_string(),
Expression::E => "e()".to_string(),
Expression::Case { .. } | Expression::SimpleCase { .. } => "CASE".to_string(),
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: &Value) -> String {
match value {
Value::Null => "null".to_string(),
Value::Boolean(value) => value.to_string(),
Value::Integer(value) => value.to_string(),
Value::Float(value) => value.to_string(),
Value::String(value) => quoted_string_column(value),
Value::List(_)
| Value::Map(_)
| Value::Node(_)
| Value::Relationship(_)
| Value::Path(_) => {
format!("{value:?}")
}
}
}
fn quoted_string_column(value: &str) -> String {
let escaped = value.replace('\\', "\\\\").replace('\'', "\\'");
format!("'{escaped}'")
}
fn order_column_index(item: &ReturnItem, returns: &[ReturnItem]) -> Result<usize> {
returns
.iter()
.position(|return_item| {
return_expression_matches(return_item, item)
|| matches!(&item.expression, ReturnExpression::Variable(variable) if return_item.alias.as_deref() == Some(variable.as_str()))
})
.ok_or_else(|| {
Error::Execution(format!(
"ORDER BY item `{}` was not projected",
expression_column(item)
))
})
}
fn return_expression_matches(left: &ReturnItem, right: &ReturnItem) -> bool {
left.expression == right.expression
}
fn node_value(node: &Node) -> Value {
Value::Node(NodeValue::stored(
node.id as u64,
node.external_id.clone(),
node.labels.clone(),
node.properties.clone(),
))
}
fn relationship_value(
storage: &dyn StorageInterface,
relationship: &Relationship,
) -> Result<Value> {
relationship_value_data(storage, relationship).map(Value::Relationship)
}
fn relationship_value_data(
storage: &dyn StorageInterface,
relationship: &Relationship,
) -> Result<RelationshipValue> {
let start = storage_node(storage, relationship.start)?
.external_id
.clone();
let end = storage_node(storage, relationship.end)?.external_id.clone();
Ok(RelationshipValue::stored(
relationship.id as u64,
relationship.start as u64,
relationship.end as u64,
relationship.external_id.clone(),
start,
end,
relationship.r#type.clone(),
relationship.properties.clone(),
))
}
fn path_value(storage: &dyn StorageInterface, path: &PathBinding) -> Result<Value> {
let nodes = path
.nodes
.iter()
.map(|node_id| {
let Value::Node(node) = node_value(storage_node(storage, *node_id)?) else {
unreachable!("node_value always returns Value::Node")
};
Ok(node)
})
.collect::<Result<Vec<_>>>()?;
let relationships = path
.relationships
.iter()
.map(|relationship_id| {
relationship_value_data(storage, storage_relationship(storage, *relationship_id)?)
})
.collect::<Result<Vec<_>>>()?;
Ok(Value::Path(PathValue {
nodes,
relationships,
}))
}
fn storage_node(storage: &dyn StorageInterface, node_id: NodeId) -> Result<&Node> {
storage.check_query_control()?;
storage
.node(node_id)
.ok_or_else(|| Error::Execution(format!("missing node id {node_id}")))
}
fn storage_relationship(
storage: &dyn StorageInterface,
relationship_id: RelationshipId,
) -> Result<&Relationship> {
storage.check_query_control()?;
storage
.relationship(relationship_id)
.ok_or_else(|| Error::Execution(format!("missing relationship id {relationship_id}")))
}
#[cfg(test)]
mod entity_value_tests {
use super::*;
#[test]
fn node_projection_preserves_the_neo4j_record_identity() {
let node = Node {
id: 42,
external_id: "node-42".to_owned(),
labels: vec!["Person".to_owned()],
properties: BTreeMap::new(),
};
let Value::Node(value) = node_value(&node) else {
panic!("expected a node value");
};
assert_eq!(value.record_id, Some(42));
assert_eq!(value.id, "node-42");
}
}
#[cfg(test)]
mod query_control_tests {
use std::cell::Cell;
use super::*;
struct CancellingStorage {
checks: Cell<usize>,
cancel_at: usize,
}
impl StorageInterface for CancellingStorage {
fn check_query_control(&self) -> Result<()> {
let checks = self.checks.get() + 1;
self.checks.set(checks);
if checks >= self.cancel_at {
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
} else {
Ok(())
}
}
fn node_ids(&self) -> Vec<NodeId> {
(0..1_024).collect()
}
fn relationship_ids(&self) -> Vec<RelationshipId> {
Vec::new()
}
fn node(&self, _id: NodeId) -> Option<&Node> {
None
}
fn relationship(&self, _id: RelationshipId) -> Option<&Relationship> {
None
}
fn outgoing_relationships(&self, _id: NodeId) -> &[RelationshipId] {
&[]
}
fn incoming_relationships(&self, _id: NodeId) -> &[RelationshipId] {
&[]
}
fn nodes_with_label(&self, _label: &str) -> &[NodeId] {
&[]
}
fn node_by_external_id(&self, _external_id: &str) -> Option<NodeId> {
None
}
fn relationship_by_external_id(&self, _external_id: &str) -> Option<RelationshipId> {
None
}
fn label_tokens(&self) -> Vec<String> {
Vec::new()
}
fn relationship_type_tokens(&self) -> Vec<String> {
Vec::new()
}
fn property_key_tokens(&self) -> Vec<String> {
Vec::new()
}
}
#[test]
fn interrupts_range_generation_at_a_batch_boundary() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
assert!(matches!(
evaluate_range_value(
Value::Integer(1),
Value::Integer(1_000_000),
None,
Some(&storage),
),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_a_procedure_catalog_scan() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 10,
};
let plan = crate::cypher::planner::plan(
crate::cypher::parser::parse_query("CALL db.labels()").unwrap(),
)
.unwrap();
assert!(matches!(
execute(&storage, plan, &Params::new()),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_range_generation_in_row_count_expressions() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 6,
};
let row_count = RowCount::Expression(Expression::Size(Box::new(Expression::Range {
start: Box::new(Expression::Literal(Value::Integer(1))),
end: Box::new(Expression::Literal(Value::Integer(1_000_000))),
step: None,
})));
assert!(matches!(
resolve_row_count(&storage, "LIMIT", &row_count, &Params::new()),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_distinct_materialization_between_rows() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let mut records = (0..3)
.map(|value| Record {
values: vec![Value::Integer(value)],
})
.collect();
assert!(matches!(
apply_distinct(&storage, &mut records, true),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let mut rows = (0..3)
.map(|value| {
BTreeMap::from([("value".to_owned(), Binding::Value(Value::Integer(value)))])
})
.collect();
assert!(matches!(
apply_row_distinct(&storage, &mut rows, true),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_long_distinct_comparison_searches() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let values = (0..(QUERY_CONTROL_COMPARISON_BATCH * 3))
.map(|value| Value::Integer(value as i64))
.collect::<Vec<_>>();
assert!(matches!(
controlled_position(&storage, &values, |value| value == &Value::Integer(-1)),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_ordering_during_comparison_batches() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let mut values = (0..QUERY_CONTROL_COMPARISON_BATCH * 4)
.rev()
.collect::<Vec<_>>();
assert!(matches!(
controlled_sort_by(&storage, &mut values, Ord::cmp),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
assert!(values.windows(2).all(|pair| pair[0] <= pair[1]));
}
#[test]
fn interrupts_variable_only_with_projection_between_rows() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let rows = (0..3)
.map(|value| Row::from([("value".to_owned(), Binding::Value(Value::Integer(value)))]))
.collect();
let projection = crate::cypher::planner::PlannedWithProjection {
distinct: false,
items: vec![ReturnItem {
expression: ReturnExpression::Variable("value".to_owned()),
alias: None,
}],
predicate: None,
order_by: Vec::new(),
skip: None,
limit: None,
};
assert!(matches!(
apply_with_projection(&storage, &Params::new(), rows, &projection),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_storage_independent_predicates_between_rows() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let mut rows = vec![Row::new(); 3];
let predicate = Predicate::Exists(Operand::Literal(Value::Integer(1)));
assert!(matches!(
filter_with_predicate(&storage, &Params::new(), &mut rows, Some(&predicate),),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_long_relationship_path_cycle_scans() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let relationships = (0..QUERY_CONTROL_COMPARISON_BATCH * 3).collect::<Vec<_>>();
assert!(matches!(
path_contains_relationship(&storage, &relationships, usize::MAX),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_long_entity_metadata_scans() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let node = Node {
id: 0,
external_id: "node".to_owned(),
labels: (0..QUERY_CONTROL_COMPARISON_BATCH * 3)
.map(|index| format!("Label{index}"))
.collect(),
properties: Default::default(),
};
let node_pattern = NodePattern {
variable: None,
labels: vec!["Missing".to_owned()],
properties: Vec::new(),
};
assert!(matches!(
node_matches(&storage, &Row::new(), &node, &node_pattern, &Params::new()),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let relationship = Relationship {
id: 0,
external_id: "relationship".to_owned(),
start: 0,
end: 1,
r#type: "Missing".to_owned(),
properties: Default::default(),
};
let relationship_pattern = RelationshipPattern {
variable: None,
types: (0..QUERY_CONTROL_COMPARISON_BATCH * 3)
.map(|index| format!("Type{index}"))
.collect(),
direction: Direction::Outgoing,
variable_length: false,
min_hops: 1,
max_hops: Some(1),
properties: Vec::new(),
};
assert!(matches!(
relationship_matches(
&storage,
&Row::new(),
&relationship,
&relationship_pattern,
&Params::new(),
),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_scalar_aggregate_row_scans() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let rows = (0..3)
.map(|value| Row::from([("value".to_owned(), Binding::Value(Value::Integer(value)))]))
.collect::<Vec<_>>();
assert!(matches!(
collect_variable_value(&storage, &rows, "value"),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let missing_rows = vec![Row::new(), Row::new(), Row::new()];
assert!(matches!(
sum_property_value(&storage, &missing_rows, "missing", "property"),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_global_aggregate_group_materialization() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let rows = vec![Row::new(); QUERY_CONTROL_COMPARISON_BATCH * 3];
assert!(matches!(
aggregate_groups(&storage, &rows, &[], &Params::new()),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn interrupts_variable_length_path_assembly() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let relationship_count = QUERY_CONTROL_COMPARISON_BATCH * 3;
let mut row = Row::from([
("start".to_owned(), Binding::Node(0)),
(
variable_length_path_segment_variable(0),
Binding::Path(PathBinding {
nodes: (0..=relationship_count).collect(),
relationships: (0..relationship_count).collect(),
}),
),
]);
let pattern = Pattern {
variable: Some("path".to_owned()),
shortest_path: None,
start: NodePattern {
variable: Some("start".to_owned()),
labels: Vec::new(),
properties: Vec::new(),
},
chains: vec![crate::cypher::ast::PatternChain {
left_variable: Some("start".to_owned()),
relationship: RelationshipPattern {
variable: None,
types: Vec::new(),
direction: Direction::Outgoing,
variable_length: true,
min_hops: 1,
max_hops: None,
properties: Vec::new(),
},
node: NodePattern {
variable: Some("end".to_owned()),
labels: Vec::new(),
properties: Vec::new(),
},
}],
};
assert!(matches!(
bind_path(&storage, &mut row, &pattern),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
assert!(!row.contains_key("path"));
}
#[test]
fn interrupts_long_in_predicate_scans() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let list = Value::List(
(0..(QUERY_CONTROL_COMPARISON_BATCH * 3))
.map(|value| Value::Integer(value as i64))
.collect(),
);
let expression = Expression::Literal(list.clone());
assert!(matches!(
evaluate_in_predicate(&expression, &Value::Integer(-1), &list, Some(&storage),),
Err(Error::Transaction(crate::TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
}
#[cfg(test)]
mod procedure_call_tests {
use std::collections::BTreeMap;
use super::{
evaluate_procedure_arguments, execute, validate_procedure_row, ProcedureHandler,
ProcedureSignature, Row,
};
use crate::api::Params;
use crate::cypher::ast::Expression;
use crate::cypher::parser::parse_query;
use crate::cypher::planner::{plan, PlannedProcedureCall};
use crate::cypher::procedure::{
ProcedureArgument, ProcedureDefault, ProcedureMode, ProcedureOutput, ProcedureRows,
ProcedureValueType,
};
use crate::error::Error;
use crate::storage_interface::EmptyEntityLookup;
use crate::value::Value;
fn empty_handler(
_storage: &dyn crate::storage_interface::StorageInterface,
_arguments: &[Value],
) -> crate::Result<ProcedureRows> {
Ok(Box::new(std::iter::empty()))
}
const TEST_ARGUMENTS: &[ProcedureArgument] = &[ProcedureArgument {
name: "limit",
value_type: ProcedureValueType::Integer,
nullable: false,
default: Some(ProcedureDefault::Integer(42)),
}];
const TEST_OUTPUTS: &[ProcedureOutput] = &[ProcedureOutput {
name: "value",
value_type: ProcedureValueType::Integer,
nullable: false,
}];
const TEST_SIGNATURE: ProcedureSignature = ProcedureSignature {
name: "test.contract",
mode: ProcedureMode::Read,
arguments: TEST_ARGUMENTS,
outputs: TEST_OUTPUTS,
description: "Test procedure contract.",
deprecated_by: None,
handler: ProcedureHandler::Read(empty_handler),
};
fn test_call(arguments: Vec<Expression>) -> PlannedProcedureCall {
PlannedProcedureCall {
name: TEST_SIGNATURE.name.to_owned(),
mode: ProcedureMode::Read,
arguments,
yields: Vec::new(),
predicate: None,
}
}
#[test]
fn executes_ping_as_standalone_and_composed_call() {
let standalone = execute(
&EmptyEntityLookup,
plan(parse_query("CALL db.ping()").expect("parse call")).expect("plan call"),
&Params::new(),
)
.expect("execute call");
assert_eq!(standalone.columns, vec!["success"]);
assert_eq!(standalone.rows[0].values, vec![Value::Boolean(true)]);
let composed = execute(
&EmptyEntityLookup,
plan(
parse_query(
"UNWIND [1, 2] AS n CALL db.ping() YIELD success AS ok \
WHERE ok = true RETURN n, ok",
)
.expect("parse call"),
)
.expect("plan call"),
&Params::new(),
)
.expect("execute call");
assert_eq!(composed.columns, vec!["n", "ok"]);
assert_eq!(composed.rows.len(), 2);
assert!(composed
.rows
.iter()
.all(|row| row.values[1] == Value::Boolean(true)));
let unwind_after_call = execute(
&EmptyEntityLookup,
plan(
parse_query(
"CALL db.ping() YIELD success AS ok \
UNWIND [1, 2] AS n RETURN n, ok",
)
.unwrap(),
)
.unwrap(),
&Params::new(),
)
.unwrap();
assert_eq!(unwind_after_call.columns, vec!["n", "ok"]);
assert_eq!(unwind_after_call.rows.len(), 2);
let after_with = execute(
&EmptyEntityLookup,
plan(
parse_query(
"UNWIND [1, 2] AS n WITH n \
CALL db.ping() YIELD success RETURN n, success",
)
.unwrap(),
)
.unwrap(),
&Params::new(),
)
.unwrap();
assert_eq!(after_with.columns, vec!["n", "success"]);
assert_eq!(after_with.rows.len(), 2);
let unwind_after_with_call = execute(
&EmptyEntityLookup,
plan(
parse_query(
"UNWIND [1, 2] AS n WITH n CALL db.ping() YIELD success \
UNWIND ['a', 'b'] AS suffix RETURN n, suffix, success",
)
.unwrap(),
)
.unwrap(),
&Params::new(),
)
.unwrap();
assert_eq!(
unwind_after_with_call.columns,
vec!["n", "suffix", "success"]
);
assert_eq!(unwind_after_with_call.rows.len(), 4);
let after_second_with = execute(
&EmptyEntityLookup,
plan(
parse_query(
"UNWIND [1, 2] AS n WITH n \
CALL db.ping() YIELD success \
WITH n, success CALL db.ping() YIELD success AS again \
RETURN n, success, again",
)
.unwrap(),
)
.unwrap(),
&Params::new(),
)
.unwrap();
assert_eq!(after_second_with.columns, vec!["n", "success", "again"]);
assert_eq!(after_second_with.rows.len(), 2);
assert!(after_second_with.rows.iter().all(|row| {
row.values[1] == Value::Boolean(true) && row.values[2] == Value::Boolean(true)
}));
}
#[test]
fn applies_defaults_and_validates_runtime_parameter_types() {
assert_eq!(
evaluate_procedure_arguments(
&EmptyEntityLookup,
&Params::new(),
&Row::new(),
&test_call(Vec::new()),
&TEST_SIGNATURE,
)
.unwrap(),
vec![Value::Integer(42)]
);
let call = test_call(vec![Expression::Parameter("limit".to_owned())]);
let valid = Params::from([("limit".to_owned(), Value::Integer(7))]);
assert_eq!(
evaluate_procedure_arguments(
&EmptyEntityLookup,
&valid,
&Row::new(),
&call,
&TEST_SIGNATURE,
)
.unwrap(),
vec![Value::Integer(7)]
);
let invalid = Params::from([("limit".to_owned(), Value::String("7".to_owned()))]);
assert!(matches!(
evaluate_procedure_arguments(
&EmptyEntityLookup,
&invalid,
&Row::new(),
&call,
&TEST_SIGNATURE,
),
Err(Error::InvalidProcedureCall { message, .. })
if message == "argument `limit` has the wrong type"
));
}
#[test]
fn rejects_malformed_handler_rows() {
validate_procedure_row(
&TEST_SIGNATURE,
&BTreeMap::from([("value".to_owned(), Value::Integer(1))]),
)
.unwrap();
for (row, expected) in [
(BTreeMap::new(), "did not produce declared field `value`"),
(
BTreeMap::from([("value".to_owned(), Value::Null)]),
"produced null for non-null field `value`",
),
(
BTreeMap::from([("value".to_owned(), Value::String("bad".to_owned()))]),
"produced the wrong type for field `value`",
),
(
BTreeMap::from([
("value".to_owned(), Value::Integer(1)),
("extra".to_owned(), Value::Boolean(true)),
]),
"produced undeclared field `extra`",
),
] {
assert!(matches!(
validate_procedure_row(&TEST_SIGNATURE, &row),
Err(Error::Execution(message)) if message.contains(expected)
));
}
}
}