use std::cell::Cell;
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::marker::PhantomData;
use std::path::Path;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use regex::Regex;
use crate::cypher::ast::{
AngleConversionMode, ComparisonOperator, CreateRelationshipStatement, CreateStatement,
DeleteStatement, Direction, Expression, ForeachStatement, InverseTrigonometricMode,
MatchClause, MergeAction, MergeBranch, MergeStatement, NodePattern, Operand, Pattern,
Predicate, Query, RelationshipPattern, RemoveItem, RemoveStatement, ReturnExpression,
ReturnItem, ReturnProjection, RoundingMode, SetItem, SetStatement, Statement, StringOperator,
StringSliceMode, TrigonometricMode, TrimMode,
};
use crate::cypher::executor::{evaluate_write_procedure_invocations, execute, WriteProcedureStage};
use crate::cypher::parser::parse_statement;
use crate::cypher::planner::plan;
use crate::cypher::procedure::{resolve as resolve_procedure, ProcedureHandler, ProcedureMode};
use crate::error::{Error, Result, TransactionErrorKind};
use crate::graph_model::{NodeId, RelationshipId};
use crate::neo4j_backend::{Neo4jBackend, Neo4jBackendSavepoint, WorkspaceUsage};
use crate::neo4j_storage::{Neo4jStorage, Neo4jWritableStorage};
use crate::storage_interface::{StorageInterface, WritableStorage};
use crate::value::{Properties, Value};
pub type Params = BTreeMap<String, Value>;
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)
}
#[derive(Clone, Debug, PartialEq)]
pub struct Record {
pub values: Vec<Value>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct QueryResult {
pub columns: Vec<String>,
pub rows: Vec<Record>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EntityId {
Node(NodeId),
Relationship(RelationshipId),
}
#[derive(Clone, Debug, Default)]
struct CreatedRelationshipRow {
relationships: BTreeMap<String, RelationshipId>,
path: Option<CreatedPath>,
}
#[derive(Clone, Debug)]
struct CreatedPath {
variable: String,
nodes: Vec<NodeId>,
relationships: Vec<RelationshipId>,
}
#[derive(Debug)]
pub struct Graph {
backend: Neo4jBackend,
query_control: Option<QueryControl>,
}
#[derive(Clone, Debug)]
struct QueryControl {
deadline: Option<Instant>,
cancellation_token: Option<CancellationToken>,
max_query_memory_bytes: Option<usize>,
query_memory_bytes: Cell<usize>,
}
impl QueryControl {
fn check(&self) -> Result<()> {
if self
.cancellation_token
.as_ref()
.is_some_and(CancellationToken::is_cancelled)
{
Err(Error::Transaction(TransactionErrorKind::Cancelled))
} else if self
.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
{
Err(Error::Transaction(TransactionErrorKind::TimedOut))
} else {
Ok(())
}
}
fn charge_memory(&self, bytes: usize) -> Result<()> {
let total = self
.query_memory_bytes
.get()
.checked_add(bytes)
.ok_or(Error::Transaction(TransactionErrorKind::ResourceLimit))?;
if self
.max_query_memory_bytes
.is_some_and(|limit| total > limit)
{
return Err(Error::Transaction(TransactionErrorKind::ResourceLimit));
}
self.query_memory_bytes.set(total);
Ok(())
}
}
struct ControlledStorage<'a> {
storage: &'a dyn StorageInterface,
control: Option<&'a QueryControl>,
}
impl StorageInterface for ControlledStorage<'_> {
fn check_query_control(&self) -> Result<()> {
self.control.map_or(Ok(()), QueryControl::check)
}
fn charge_query_memory(&self, bytes: usize) -> Result<()> {
self.control
.map_or(Ok(()), |control| control.charge_memory(bytes))
}
fn database_metadata(&self) -> Option<&crate::storage_interface::DatabaseMetadata> {
self.storage.database_metadata()
}
fn schema_metadata(&self) -> Option<&crate::storage_interface::SchemaMetadata> {
self.storage.schema_metadata()
}
fn node_ids(&self) -> Vec<NodeId> {
self.storage.node_ids()
}
fn relationship_ids(&self) -> Vec<RelationshipId> {
self.storage.relationship_ids()
}
fn node(&self, id: NodeId) -> Option<&crate::graph_model::Node> {
self.storage.node(id)
}
fn relationship(&self, id: RelationshipId) -> Option<&crate::graph_model::Relationship> {
self.storage.relationship(id)
}
fn outgoing_relationships(&self, id: NodeId) -> &[RelationshipId] {
self.storage.outgoing_relationships(id)
}
fn incoming_relationships(&self, id: NodeId) -> &[RelationshipId] {
self.storage.incoming_relationships(id)
}
fn nodes_with_label(&self, label: &str) -> &[NodeId] {
self.storage.nodes_with_label(label)
}
fn node_by_external_id(&self, external_id: &str) -> Option<NodeId> {
self.storage.node_by_external_id(external_id)
}
fn relationship_by_external_id(&self, external_id: &str) -> Option<RelationshipId> {
self.storage.relationship_by_external_id(external_id)
}
fn label_tokens(&self) -> Vec<String> {
self.storage.label_tokens()
}
fn relationship_type_tokens(&self) -> Vec<String> {
self.storage.relationship_type_tokens()
}
fn property_key_tokens(&self) -> Vec<String> {
self.storage.property_key_tokens()
}
fn node_property_type(&self, id: NodeId, property_key: &str) -> Option<String> {
self.storage.node_property_type(id, property_key)
}
fn relationship_property_type(&self, id: RelationshipId, property_key: &str) -> Option<String> {
self.storage.relationship_property_type(id, property_key)
}
}
#[derive(Clone, Debug, Default)]
pub struct TransactionOptions {
pub timeout: Option<Duration>,
pub deadline: Option<Instant>,
pub max_workspace_bytes: Option<usize>,
pub max_records: Option<usize>,
pub max_query_memory_bytes: Option<usize>,
pub spill_threshold_bytes: Option<usize>,
pub max_spill_bytes: Option<u64>,
pub max_journal_bytes: Option<u64>,
pub cancellation_token: Option<CancellationToken>,
pub read_only: bool,
}
#[derive(Clone, Debug, Default)]
pub struct CancellationToken {
cancelled: Arc<AtomicBool>,
}
impl CancellationToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.cancelled.store(true, AtomicOrdering::Release);
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(AtomicOrdering::Acquire)
}
}
#[derive(Debug)]
#[must_use = "dropping a transaction without committing rolls it back"]
pub struct Transaction<'graph> {
graph: &'graph mut Graph,
state: TransactionHandleState,
id: u64,
next_savepoint_id: u64,
savepoints: Vec<TransactionSavepoint>,
deadline: Option<Instant>,
cancellation_token: Option<CancellationToken>,
locally_cancelled: bool,
max_workspace_bytes: Option<usize>,
max_records: Option<usize>,
max_query_memory_bytes: Option<usize>,
read_only: bool,
not_send: PhantomData<Rc<()>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[must_use = "retain the token to roll back to or release this savepoint"]
pub struct Savepoint {
transaction_id: u64,
id: u64,
}
#[derive(Debug)]
struct TransactionSavepoint {
token: Savepoint,
backend: Neo4jBackendSavepoint,
usage: WorkspaceUsage,
}
static NEXT_TRANSACTION_ID: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TransactionHandleState {
Active,
Failed(TransactionErrorKind),
Completed,
}
impl Graph {
pub fn open_neo4j(database_directory: impl AsRef<Path>) -> Result<Self> {
Ok(Self {
backend: Neo4jBackend::ReadOnly(Box::new(Neo4jStorage::open(database_directory)?)),
query_control: None,
})
}
pub fn open_neo4j_writable(database_directory: impl AsRef<Path>) -> Result<Self> {
Ok(Self {
backend: Neo4jBackend::Writable(Box::new(Neo4jWritableStorage::open(
database_directory,
)?)),
query_control: None,
})
}
pub fn query(&mut self, query: &str, params: Params) -> Result<QueryResult> {
let statement = parse_statement(query)?;
let is_write = is_write_statement(&statement)?;
if !is_write {
self.backend.refresh_read_view()?;
return self.execute_statement(statement, ¶ms);
}
self.backend
.begin_transaction(None, None, None, None, None, None)?;
match self.execute_statement(statement, ¶ms) {
Ok(result) => {
self.backend.commit_transaction()?;
Ok(result)
}
Err(error) => {
self.backend.mark_transaction_failed();
self.backend.rollback_transaction()?;
Err(error)
}
}
}
pub fn transaction(&mut self) -> Result<Transaction<'_>> {
self.transaction_with_options(TransactionOptions::default())
}
pub fn transaction_with_options(
&mut self,
options: TransactionOptions,
) -> Result<Transaction<'_>> {
let id = NEXT_TRANSACTION_ID
.try_update(AtomicOrdering::Relaxed, AtomicOrdering::Relaxed, |id| {
id.checked_add(1)
})
.map_err(|_| Error::Execution("transaction identifier space exhausted".to_owned()))?;
let timeout_deadline = options
.timeout
.map(|timeout| {
Instant::now().checked_add(timeout).ok_or_else(|| {
Error::Execution("transaction timeout exceeds the supported range".to_owned())
})
})
.transpose()?;
let deadline = match (options.deadline, timeout_deadline) {
(Some(deadline), Some(timeout_deadline)) => Some(deadline.min(timeout_deadline)),
(deadline, timeout_deadline) => deadline.or(timeout_deadline),
};
self.backend.begin_transaction(
options.max_workspace_bytes,
options.max_records,
options.spill_threshold_bytes,
options.max_spill_bytes,
options.max_journal_bytes,
Some(id),
)?;
Ok(Transaction {
graph: self,
state: TransactionHandleState::Active,
id,
next_savepoint_id: 1,
savepoints: Vec::new(),
deadline,
cancellation_token: options.cancellation_token,
locally_cancelled: false,
max_workspace_bytes: options.max_workspace_bytes,
max_records: options.max_records,
max_query_memory_bytes: options.max_query_memory_bytes,
read_only: options.read_only,
not_send: PhantomData,
})
}
pub fn run_transaction<F>(&mut self, max_retries: usize, operation: F) -> Result<()>
where
F: FnMut(&mut Transaction<'_>) -> Result<()>,
{
self.run_transaction_with_options(TransactionOptions::default(), max_retries, operation)
}
pub fn run_transaction_with_options<F>(
&mut self,
options: TransactionOptions,
max_retries: usize,
mut operation: F,
) -> Result<()>
where
F: FnMut(&mut Transaction<'_>) -> Result<()>,
{
let mut retries = 0;
loop {
let mut transaction = self.transaction_with_options(options.clone())?;
let result = match operation(&mut transaction) {
Ok(()) => transaction.commit(),
Err(error) => {
drop(transaction);
Err(error)
}
};
match result {
Err(Error::Transaction(TransactionErrorKind::Conflict))
if retries < max_retries =>
{
retries += 1;
}
result => return result,
}
}
}
fn execute_statement(&mut self, statement: Statement, params: &Params) -> Result<QueryResult> {
if !self.backend.is_writable()
&& !matches!(&statement, Statement::Single(_) | Statement::Union { .. })
{
return Err(Error::UnsupportedWriteQuery(
"Neo4j storage is read-only".to_owned(),
));
}
match statement {
Statement::Single(query) => {
let plan = plan(query)?;
self.execute_plan(plan, params)
}
Statement::Create(create) => self.execute_create(create, params),
Statement::CreateRelationship(create) => {
self.execute_create_relationship(create, params)
}
Statement::Set(set) => self.execute_set(set, params),
Statement::Foreach(foreach) => self.execute_foreach(foreach, params),
Statement::Delete(delete) => self.execute_delete(delete, params),
Statement::Remove(remove) => self.execute_remove(remove, params),
Statement::Merge(merge) => self.execute_merge(merge, params),
Statement::Union { first, parts } => {
let mut result = self.execute_plan(plan(first)?, params)?;
let columns = result.columns.clone();
for part in parts {
let mut next = self.execute_plan(plan(part.query)?, params)?;
if next.columns != columns {
return Err(Error::Validation(format!(
"UNION query columns must match: expected {:?}, got {:?}",
columns, next.columns
)));
}
result.rows.append(&mut next.rows);
if !part.all {
deduplicate_rows(&self.read_storage(), &mut result.rows)?;
}
}
Ok(result)
}
}
}
fn read_storage(&self) -> ControlledStorage<'_> {
ControlledStorage {
storage: self.backend.read(),
control: self.query_control.as_ref(),
}
}
fn execute_plan(
&mut self,
mut plan: crate::cypher::planner::Plan,
params: &Params,
) -> Result<QueryResult> {
let procedure_stages = [
&plan.procedure_calls,
&plan.post_with_procedure_calls,
&plan.post_with_with_procedure_calls,
];
let has_write = procedure_stages
.iter()
.flat_map(|calls| calls.iter())
.any(|call| call.mode == ProcedureMode::Write);
if has_write {
if procedure_stages
.iter()
.flat_map(|calls| calls.iter())
.any(|call| call.mode != ProcedureMode::Write)
{
return Err(Error::Validation(
"mixing READ and WRITE procedures in one query is not supported".to_owned(),
));
}
if procedure_stages
.iter()
.filter(|calls| !calls.is_empty())
.count()
!= 1
{
return Err(Error::Validation(
"WRITE procedures in multiple query stages are not supported".to_owned(),
));
}
let invocations =
evaluate_write_procedure_invocations(&self.read_storage(), params, &plan)?;
let calls = match invocations.stage {
WriteProcedureStage::Initial => &plan.procedure_calls,
WriteProcedureStage::PostWith => &plan.post_with_procedure_calls,
WriteProcedureStage::PostSecondWith => &plan.post_with_with_procedure_calls,
};
for (call, arguments_by_row) in calls.iter().zip(invocations.arguments_by_call) {
let signature = resolve_procedure(&call.name)?;
let ProcedureHandler::Write(handler) = signature.handler else {
return Err(Error::Validation(format!(
"procedure `{}` does not have a WRITE handler",
call.name
)));
};
for arguments in arguments_by_row {
self.check_query_control()?;
handler(self.write_storage()?, &arguments)?;
}
}
if plan.returns.is_empty() {
return Ok(QueryResult {
columns: Vec::new(),
rows: Vec::new(),
});
}
match invocations.stage {
WriteProcedureStage::Initial => plan.procedure_calls.clear(),
WriteProcedureStage::PostWith => plan.post_with_procedure_calls.clear(),
WriteProcedureStage::PostSecondWith => plan.post_with_with_procedure_calls.clear(),
}
}
execute(&self.read_storage(), plan, params)
}
fn check_query_control(&self) -> Result<()> {
self.query_control
.as_ref()
.map_or(Ok(()), QueryControl::check)
}
fn execute_controlled_statement(
&mut self,
statement: Statement,
params: &Params,
control: QueryControl,
) -> Result<QueryResult> {
debug_assert!(self.query_control.is_none());
self.query_control = Some(control);
let result = self.execute_statement(statement, params);
self.query_control = None;
result
}
fn write_storage(&mut self) -> Result<&mut dyn WritableStorage> {
self.backend.write()
}
fn execute_create(&mut self, create: CreateStatement, params: &Params) -> Result<QueryResult> {
let variable = create.node.variable.clone();
let properties = create_properties(&self.read_storage(), &create.node, params)?;
let node_id = self
.write_storage()?
.create_node(create.node.labels.clone(), properties)?;
let returns = create_returns(&create.returns, variable.as_deref())?;
let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
let row = returns
.iter()
.map(|item| {
project_created_item(
&self.read_storage(),
node_id,
variable.as_deref(),
item,
params,
)
})
.collect::<Result<Vec<_>>>()?;
Ok(QueryResult {
columns,
rows: vec![Record { values: row }],
})
}
fn execute_create_relationship(
&mut self,
create: CreateRelationshipStatement,
params: &Params,
) -> Result<QueryResult> {
let create_patterns = relationship_create_patterns(&create.pattern)?;
let relationship_variables = relationship_create_variables(&create_patterns);
let endpoint_variables = relationship_create_endpoint_variables(&create_patterns);
let endpoint_query = query_from_matches(
create.matches.clone(),
ReturnProjection::Items(element_id_return_items(&endpoint_variables)),
)?;
let endpoint_result = self.execute_plan(plan(endpoint_query)?, params)?;
let mut created_relationships = Vec::new();
for row in endpoint_result.rows {
self.check_query_control()?;
let ids = entity_ids_from_row(
&self.read_storage(),
&endpoint_result.columns,
&row,
&BTreeSet::new(),
)?;
let mut created_row = CreatedRelationshipRow::default();
let mut path_nodes = Vec::new();
let mut path_relationships = Vec::new();
if create.pattern.variable.is_some() {
let start_id =
node_id_from_entities(&ids, &create_patterns[0].start_variable, "start")?;
path_nodes.push(start_id);
}
for create_pattern in &create_patterns {
self.check_query_control()?;
let start = node_id_from_entities(&ids, &create_pattern.start_variable, "start")?;
let end = node_id_from_entities(&ids, &create_pattern.end_variable, "end")?;
let (start, end) =
relationship_write_endpoints(start, end, create_pattern.relationship.direction);
let relationship_type = relationship_create_type(&create_pattern.relationship)?;
let properties = relationship_properties_with_entities(
&self.read_storage(),
&ids,
&create_pattern.relationship,
params,
)?;
let relationship_id = self.write_storage()?.create_relationship(
start,
end,
relationship_type,
properties,
)?;
if let Some(variable) = &create_pattern.relationship.variable {
created_row
.relationships
.insert(variable.clone(), relationship_id);
}
if create.pattern.variable.is_some() {
let end_id = node_id_from_entities(&ids, &create_pattern.end_variable, "end")?;
path_nodes.push(end_id);
path_relationships.push(relationship_id);
}
}
if let Some(variable) = &create.pattern.variable {
created_row.path = Some(CreatedPath {
variable: variable.clone(),
nodes: path_nodes,
relationships: path_relationships,
});
}
created_relationships.push(created_row);
}
let returns = create_relationship_returns(
&create.returns,
create.pattern.variable.as_deref(),
&relationship_variables,
)?;
let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
let rows = created_relationships
.iter()
.map(|relationship_ids| {
returns
.iter()
.map(|item| {
project_created_relationships_item(
&self.read_storage(),
relationship_ids,
item,
params,
)
})
.collect::<Result<Vec<_>>>()
.map(|values| Record { values })
})
.collect::<Result<Vec<_>>>()?;
Ok(QueryResult { columns, rows })
}
fn execute_set(&mut self, set: SetStatement, params: &Params) -> Result<QueryResult> {
let relationship_variables = matched_relationship_variables(&set.matches);
let target_variables = set
.items
.iter()
.map(set_item_variable)
.collect::<BTreeSet<_>>();
let target_items = target_variables
.iter()
.map(|variable| ReturnItem {
expression: ReturnExpression::ElementId(variable.clone()),
alias: Some(variable.clone()),
})
.collect::<Vec<_>>();
let target_query =
query_from_matches(set.matches.clone(), ReturnProjection::Items(target_items))?;
let target_result = self.execute_plan(plan(target_query)?, params)?;
let mut matched_rows = Vec::<BTreeMap<String, EntityId>>::new();
for row in &target_result.rows {
self.check_query_control()?;
let mut ids = BTreeMap::new();
for (index, variable) in target_result.columns.iter().enumerate() {
match row.values.get(index) {
Some(Value::String(external_id)) => {
let entity_id = entity_id_from_external_id(
&self.read_storage(),
external_id,
relationship_variables.contains(variable),
)?;
ids.insert(variable.clone(), entity_id);
}
Some(Value::Null) => {}
_ => {
return Err(Error::Validation(
"SET currently supports node and relationship property assignments"
.to_string(),
))
}
}
}
matched_rows.push(ids);
}
for ids in &matched_rows {
self.check_query_control()?;
for item in &set.items {
let Some(entity_id) = ids.get(&set_item_variable(item)).copied() else {
continue;
};
apply_set_item(self.write_storage()?, ids, entity_id, item, params)?;
}
}
let returns = set_returns(&set.returns, &target_variables)?;
let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
let rows = matched_rows
.iter()
.map(|ids| {
returns
.iter()
.map(|item| project_set_item(&self.read_storage(), ids, item, params))
.collect::<Result<Vec<_>>>()
.map(|values| Record { values })
})
.collect::<Result<Vec<_>>>()?;
Ok(QueryResult { columns, rows })
}
fn execute_foreach(
&mut self,
foreach: ForeachStatement,
params: &Params,
) -> Result<QueryResult> {
let relationship_variables = matched_relationship_variables(&foreach.matches);
let mut target_variables = BTreeSet::<String>::new();
for item in &foreach.items {
target_variables.insert(set_item_variable(item));
target_variables.extend(collect_set_item_variables(item));
}
for variable in collect_expression_variables(&foreach.expression) {
target_variables.insert(variable);
}
target_variables.remove(&foreach.variable);
let target_items = target_variables
.iter()
.map(|variable| ReturnItem {
expression: ReturnExpression::ElementId(variable.clone()),
alias: Some(variable.clone()),
})
.collect::<Vec<_>>();
let target_query = query_from_matches(
foreach.matches.clone(),
ReturnProjection::Items(target_items),
)?;
let target_result = self.execute_plan(plan(target_query)?, params)?;
let mut matched_rows = Vec::<BTreeMap<String, EntityId>>::new();
for row in &target_result.rows {
self.check_query_control()?;
let ids = entity_ids_from_row(
&self.read_storage(),
&target_result.columns,
row,
&relationship_variables,
)?;
matched_rows.push(ids);
}
for ids in &matched_rows {
self.check_query_control()?;
let list_value = evaluate_write_expression_with_entities(
&self.read_storage(),
ids,
&foreach.expression,
params,
)?;
let Value::List(values) = list_value else {
return Err(Error::Validation(
"FOREACH expression must evaluate to a list".to_string(),
));
};
for value in values {
self.check_query_control()?;
for item in &foreach.items {
let Some(entity_id) = ids.get(&set_item_variable(item)).copied() else {
continue;
};
let item = substitute_set_item_value(item, &foreach.variable, &value);
apply_set_item(self.write_storage()?, ids, entity_id, &item, params)?;
}
}
}
let returns = set_returns(&foreach.returns, &target_variables)?;
let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
let rows = matched_rows
.iter()
.map(|ids| {
returns
.iter()
.map(|item| project_set_item(&self.read_storage(), ids, item, params))
.collect::<Result<Vec<_>>>()
.map(|values| Record { values })
})
.collect::<Result<Vec<_>>>()?;
Ok(QueryResult { columns, rows })
}
fn execute_delete(&mut self, delete: DeleteStatement, params: &Params) -> Result<QueryResult> {
let relationship_variables = matched_relationship_variables(&delete.matches);
let target_items = delete
.variables
.iter()
.map(|variable| ReturnItem {
expression: ReturnExpression::ElementId(variable.clone()),
alias: Some(variable.clone()),
})
.collect::<Vec<_>>();
let target_query = query_from_matches(
delete.matches.clone(),
ReturnProjection::Items(target_items),
)?;
let target_result = self.execute_plan(plan(target_query)?, params)?;
let mut relationship_ids = BTreeSet::new();
let mut node_ids = BTreeSet::new();
for row in &target_result.rows {
self.check_query_control()?;
for (variable, value) in delete.variables.iter().zip(&row.values) {
let Value::String(external_id) = value else {
continue;
};
if relationship_variables.contains(variable) {
let relationship_id = self
.read_storage()
.relationship_by_external_id(external_id)
.ok_or_else(|| {
Error::Validation(format!(
"DELETE relationship `{variable}` is no longer available"
))
})?;
relationship_ids.insert(relationship_id);
} else {
let node_id = self
.read_storage()
.node_by_external_id(external_id)
.ok_or_else(|| {
Error::Validation(format!(
"DELETE node `{variable}` is no longer available"
))
})?;
node_ids.insert(node_id);
}
}
}
for relationship_id in relationship_ids {
self.check_query_control()?;
self.write_storage()?.delete_relationship(relationship_id)?;
}
for node_id in node_ids {
self.check_query_control()?;
if delete.detach {
self.write_storage()?.detach_delete_node(node_id)?;
} else {
self.write_storage()?.delete_node(node_id)?;
}
}
Ok(QueryResult {
columns: Vec::new(),
rows: Vec::new(),
})
}
fn execute_remove(&mut self, remove: RemoveStatement, params: &Params) -> Result<QueryResult> {
let relationship_variables = matched_relationship_variables(&remove.matches);
let target_variables = remove
.items
.iter()
.map(remove_item_variable)
.collect::<BTreeSet<_>>();
let target_items = target_variables
.iter()
.map(|variable| ReturnItem {
expression: ReturnExpression::ElementId(variable.clone()),
alias: Some(variable.clone()),
})
.collect::<Vec<_>>();
let target_query = query_from_matches(
remove.matches.clone(),
ReturnProjection::Items(target_items),
)?;
let target_result = self.execute_plan(plan(target_query)?, params)?;
let mut matched_rows = Vec::<BTreeMap<String, EntityId>>::new();
for row in &target_result.rows {
self.check_query_control()?;
let mut ids = BTreeMap::new();
for (index, variable) in target_result.columns.iter().enumerate() {
match row.values.get(index) {
Some(Value::String(external_id)) => {
let entity_id = entity_id_from_external_id(
&self.read_storage(),
external_id,
relationship_variables.contains(variable),
)?;
ids.insert(variable.clone(), entity_id);
}
Some(Value::Null) => {}
_ => {
return Err(Error::Validation(
"REMOVE currently supports node and relationship property removals"
.to_string(),
))
}
}
}
matched_rows.push(ids);
}
for ids in &matched_rows {
self.check_query_control()?;
for item in &remove.items {
let Some(entity_id) = ids.get(&remove_item_variable(item)).copied() else {
continue;
};
apply_remove_item(self.write_storage()?, entity_id, item)?;
}
}
let returns = set_returns(&remove.returns, &target_variables)?;
let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
let rows = matched_rows
.iter()
.map(|ids| {
returns
.iter()
.map(|item| project_set_item(&self.read_storage(), ids, item, params))
.collect::<Result<Vec<_>>>()
.map(|values| Record { values })
})
.collect::<Result<Vec<_>>>()?;
Ok(QueryResult { columns, rows })
}
fn execute_merge(&mut self, merge: MergeStatement, params: &Params) -> Result<QueryResult> {
match merge {
MergeStatement::Node {
node,
actions,
returns,
} => self.execute_merge_node(node, actions, returns, params),
MergeStatement::Relationship {
matches,
pattern,
actions,
returns,
} => self.execute_merge_relationship(matches, pattern, actions, returns, params),
}
}
fn execute_merge_node(
&mut self,
node: NodePattern,
actions: Vec<MergeAction>,
returns: ReturnProjection,
params: &Params,
) -> Result<QueryResult> {
let variable = node.variable.clone();
let properties = create_properties(&self.read_storage(), &node, params)?;
let (node_id, created) = match find_merge_node(&self.read_storage(), &node, &properties)? {
Some(node_id) => (node_id, false),
None => (
self.write_storage()?
.create_node(node.labels.clone(), properties.clone())?,
true,
),
};
if let Some(variable) = variable.as_deref() {
apply_merge_actions(
self.write_storage()?,
EntityId::Node(node_id),
variable,
created,
&actions,
params,
)?;
} else if !actions.is_empty() {
return Err(Error::Validation(
"MERGE actions require a pattern variable".to_string(),
));
}
let returns = create_returns(&returns, variable.as_deref())?;
let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
let row = returns
.iter()
.map(|item| {
project_created_item(
&self.read_storage(),
node_id,
variable.as_deref(),
item,
params,
)
})
.collect::<Result<Vec<_>>>()?;
Ok(QueryResult {
columns,
rows: vec![Record { values: row }],
})
}
fn execute_merge_relationship(
&mut self,
matches: Vec<MatchClause>,
pattern: Pattern,
actions: Vec<MergeAction>,
returns: ReturnProjection,
params: &Params,
) -> Result<QueryResult> {
let merge_pattern = relationship_create_pattern(&pattern)?;
let start_variable = merge_pattern.start_variable.clone();
let end_variable = merge_pattern.end_variable.clone();
let relationship_variable = merge_pattern.relationship.variable.clone();
let endpoint_variables =
relationship_merge_endpoint_variables(&matches, &start_variable, &end_variable);
let endpoint_query = query_from_matches(
matches,
ReturnProjection::Items(element_id_return_items(&endpoint_variables)),
)?;
let endpoint_result = self.execute_plan(plan(endpoint_query)?, params)?;
let relationship_type = relationship_create_type(&merge_pattern.relationship)?;
let mut relationship_ids = Vec::new();
for row in endpoint_result.rows {
self.check_query_control()?;
let ids = entity_ids_from_row(
&self.read_storage(),
&endpoint_result.columns,
&row,
&BTreeSet::new(),
)?;
let start = node_id_from_entities(&ids, &start_variable, "start")?;
let end = node_id_from_entities(&ids, &end_variable, "end")?;
let direction = merge_pattern.relationship.direction;
let (start, end) = relationship_write_endpoints(start, end, direction);
let properties = relationship_properties_with_entities(
&self.read_storage(),
&ids,
&merge_pattern.relationship,
params,
)?;
let (relationship_id, created) = match find_merge_relationship(
&self.read_storage(),
start,
end,
direction,
&merge_pattern.relationship.types,
&properties,
)? {
Some(relationship_id) => (relationship_id, false),
None => (
self.write_storage()?.create_relationship(
start,
end,
relationship_type.clone(),
properties.clone(),
)?,
true,
),
};
if let Some(variable) = relationship_variable.as_deref() {
apply_merge_actions(
self.write_storage()?,
EntityId::Relationship(relationship_id),
variable,
created,
&actions,
params,
)?;
} else if !actions.is_empty() {
return Err(Error::Validation(
"MERGE actions require a relationship variable".to_string(),
));
}
relationship_ids.push(relationship_id);
}
let relationship_variables = relationship_variable.iter().cloned().collect::<Vec<_>>();
let returns = create_relationship_returns(&returns, None, &relationship_variables)?;
let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
let rows = relationship_ids
.iter()
.map(|relationship_id| {
returns
.iter()
.map(|item| {
project_created_relationship_item(
&self.read_storage(),
*relationship_id,
relationship_variable.as_deref(),
item,
params,
)
})
.collect::<Result<Vec<_>>>()
.map(|values| Record { values })
})
.collect::<Result<Vec<_>>>()?;
Ok(QueryResult { columns, rows })
}
}
impl Transaction<'_> {
pub fn query(&mut self, query: &str, params: Params) -> Result<QueryResult> {
match self.state {
TransactionHandleState::Active => {}
TransactionHandleState::Failed(kind) => {
return Err(Error::Transaction(kind));
}
TransactionHandleState::Completed => unreachable!("completed transaction is consumed"),
}
self.check_control_state()?;
let control = QueryControl {
deadline: self.deadline,
cancellation_token: self.cancellation_token.clone(),
max_query_memory_bytes: self.max_query_memory_bytes,
query_memory_bytes: Cell::new(0),
};
let result = parse_statement(query).and_then(|statement| {
if self.read_only && is_write_statement(&statement)? {
return Err(Error::AccessMode);
}
self.graph
.execute_controlled_statement(statement, ¶ms, control)
});
if let Err(error) = &result {
let kind = match error {
Error::Transaction(
kind @ (TransactionErrorKind::ResourceLimit
| TransactionErrorKind::TimedOut
| TransactionErrorKind::Cancelled),
) => *kind,
_ => TransactionErrorKind::RollbackOnly,
};
self.fail(kind);
return result;
}
self.check_control_state()?;
self.check_resource_limits(WorkspaceUsage::default())?;
result
}
pub fn cancel(&mut self) {
self.locally_cancelled = true;
if self.state == TransactionHandleState::Active {
self.fail(TransactionErrorKind::Cancelled);
}
}
pub fn savepoint(&mut self) -> Result<Savepoint> {
if let TransactionHandleState::Failed(kind) = self.state {
return Err(Error::Transaction(kind));
}
self.check_control_state()?;
let usage = self.savepoint_usage()?;
self.check_resource_limits(usage)?;
let backend = self.graph.backend.savepoint()?;
let token = Savepoint {
transaction_id: self.id,
id: self.next_savepoint_id,
};
self.next_savepoint_id = self
.next_savepoint_id
.checked_add(1)
.ok_or_else(|| Error::Execution("savepoint identifier space exhausted".to_owned()))?;
self.savepoints.push(TransactionSavepoint {
token,
backend,
usage,
});
self.sync_backend_workspace_limits()?;
Ok(token)
}
pub fn rollback_to(&mut self, savepoint: Savepoint) -> Result<()> {
let index = self.savepoint_index(savepoint)?;
self.graph
.backend
.rollback_to_savepoint(&self.savepoints[index].backend)?;
self.savepoints.truncate(index + 1);
self.state = TransactionHandleState::Active;
self.sync_backend_workspace_limits()?;
Ok(())
}
pub fn release_savepoint(&mut self, savepoint: Savepoint) -> Result<()> {
let index = self.savepoint_index(savepoint)?;
self.savepoints.remove(index);
self.sync_backend_workspace_limits()?;
Ok(())
}
fn savepoint_index(&self, savepoint: Savepoint) -> Result<usize> {
if savepoint.transaction_id != self.id {
return Err(Error::Transaction(TransactionErrorKind::InvalidSavepoint));
}
self.savepoints
.iter()
.position(|checkpoint| checkpoint.token == savepoint)
.ok_or(Error::Transaction(TransactionErrorKind::InvalidSavepoint))
}
fn check_control_state(&mut self) -> Result<()> {
let failure = if self.locally_cancelled
|| self
.cancellation_token
.as_ref()
.is_some_and(CancellationToken::is_cancelled)
{
Some(TransactionErrorKind::Cancelled)
} else if self
.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
{
Some(TransactionErrorKind::TimedOut)
} else {
None
};
if let Some(kind) = failure {
self.fail(kind);
Err(Error::Transaction(kind))
} else {
Ok(())
}
}
fn check_resource_limits(&mut self, additional: WorkspaceUsage) -> Result<()> {
let usage = (|| {
let mut usage = self
.graph
.backend
.workspace_usage()?
.checked_add(additional)?;
usage = usage.checked_add(self.retained_savepoint_usage()?)?;
Ok::<_, Error>(usage)
})();
let usage = match usage {
Ok(usage) => usage,
Err(error) => {
self.fail(TransactionErrorKind::ResourceLimit);
return Err(error);
}
};
if self
.max_workspace_bytes
.is_some_and(|limit| usage.bytes > limit)
|| self.max_records.is_some_and(|limit| usage.records > limit)
{
self.fail(TransactionErrorKind::ResourceLimit);
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
} else {
Ok(())
}
}
fn retained_savepoint_usage(&self) -> Result<WorkspaceUsage> {
self.savepoints
.iter()
.try_fold(WorkspaceUsage::default(), |usage, savepoint| {
usage.checked_add(savepoint.usage)
})
}
fn savepoint_usage(&self) -> Result<WorkspaceUsage> {
self.graph
.backend
.savepoint_usage()?
.checked_add(WorkspaceUsage {
bytes: std::mem::size_of::<TransactionSavepoint>(),
records: 0,
})
}
fn sync_backend_workspace_limits(&mut self) -> Result<()> {
let limits = (|| {
let retained = self.retained_savepoint_usage()?;
let max_workspace_bytes = self
.max_workspace_bytes
.map(|limit| {
limit
.checked_sub(retained.bytes)
.ok_or(Error::Transaction(TransactionErrorKind::ResourceLimit))
})
.transpose()?;
let max_records = self
.max_records
.map(|limit| {
limit
.checked_sub(retained.records)
.ok_or(Error::Transaction(TransactionErrorKind::ResourceLimit))
})
.transpose()?;
Ok::<_, Error>((max_workspace_bytes, max_records))
})();
let (max_workspace_bytes, max_records) = match limits {
Ok(limits) => limits,
Err(error) => {
self.fail(TransactionErrorKind::ResourceLimit);
return Err(error);
}
};
if let Err(error) = self
.graph
.backend
.set_workspace_limits(max_workspace_bytes, max_records)
{
self.fail(TransactionErrorKind::ResourceLimit);
return Err(error);
}
Ok(())
}
fn fail(&mut self, kind: TransactionErrorKind) {
self.state = TransactionHandleState::Failed(kind);
self.graph.backend.mark_transaction_failed();
}
pub fn commit(mut self) -> Result<()> {
if let TransactionHandleState::Failed(kind) = self.state {
return Err(Error::Transaction(kind));
}
self.check_control_state()?;
self.check_resource_limits(WorkspaceUsage::default())?;
let result = self.graph.backend.commit_transaction();
self.state = TransactionHandleState::Completed;
result
}
pub fn rollback(mut self) -> Result<()> {
let result = self.graph.backend.rollback_transaction();
self.state = TransactionHandleState::Completed;
result
}
}
impl Drop for Transaction<'_> {
fn drop(&mut self) {
if self.state != TransactionHandleState::Completed {
let _ = self.graph.backend.rollback_transaction();
self.state = TransactionHandleState::Completed;
}
}
}
fn is_write_statement(statement: &Statement) -> Result<bool> {
fn query_writes(query: &Query) -> Result<bool> {
query
.procedure_calls
.iter()
.chain(query.post_with_procedure_calls.iter())
.chain(query.post_with_with_procedure_calls.iter())
.try_fold(false, |writes, call| {
Ok(writes || resolve_procedure(&call.name)?.mode == ProcedureMode::Write)
})
}
match statement {
Statement::Single(query) => query_writes(query),
Statement::Union { first, parts } => {
if query_writes(first)? {
return Ok(true);
}
for part in parts {
if query_writes(&part.query)? {
return Ok(true);
}
}
Ok(false)
}
_ => Ok(true),
}
}
fn create_properties(
storage: &dyn StorageInterface,
node: &NodePattern,
params: &Params,
) -> Result<Properties> {
let ids = BTreeMap::new();
node.properties
.iter()
.map(|property| {
evaluate_write_expression_with_entities(storage, &ids, &property.expression, params)
.map(|value| (property.key.clone(), value))
})
.collect()
}
#[cfg(test)]
mod transaction_option_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(TransactionErrorKind::Cancelled))
} else {
Ok(())
}
}
fn node_ids(&self) -> Vec<NodeId> {
Vec::new()
}
fn relationship_ids(&self) -> Vec<RelationshipId> {
Vec::new()
}
fn node(&self, _id: NodeId) -> Option<&crate::graph_model::Node> {
None
}
fn relationship(&self, _id: RelationshipId) -> Option<&crate::graph_model::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 read_procedures_use_public_api_and_transaction_read_view() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let empty = graph.query("CALL db.labels()", Params::new()).unwrap();
assert_eq!(empty.columns, ["label"]);
assert!(empty.rows.is_empty());
let initial_info = graph.query("CALL db.info()", Params::new()).unwrap();
assert_eq!(initial_info.columns, ["id", "name", "creationDate"]);
assert_eq!(initial_info.rows.len(), 1);
assert_eq!(
initial_info.rows[0].values[1],
Value::String("neo4j".to_owned())
);
let post_with_ping = graph
.query(
"UNWIND [1, 2] AS n WITH n \
CALL db.ping() YIELD success RETURN n, success",
Params::new(),
)
.unwrap();
assert_eq!(post_with_ping.columns, ["n", "success"]);
assert_eq!(post_with_ping.rows.len(), 2);
let mut transaction = graph.transaction().unwrap();
transaction
.query("CREATE (:Start {id: 1, name: 'start'})", Params::new())
.unwrap();
transaction
.query("CREATE (:Finish {id: 2})", Params::new())
.unwrap();
transaction
.query(
"MATCH (a:Start {id: 1}), (b:Finish {id: 2}) \
CREATE (a)-[:CONNECTS]->(b)",
Params::new(),
)
.unwrap();
let match_after_call = transaction
.query(
"CALL db.ping() YIELD success MATCH (start:Start) \
RETURN start.id, success",
Params::new(),
)
.unwrap();
assert_eq!(match_after_call.columns, ["start.id", "success"]);
assert_eq!(
match_after_call.rows[0].values,
[Value::Integer(1), Value::Boolean(true)]
);
let labels = transaction
.query("CALL db.labels() YIELD label RETURN label", Params::new())
.unwrap();
assert_eq!(labels.columns, ["label"]);
assert_eq!(
labels
.rows
.iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>(),
[
Value::String("Start".to_owned()),
Value::String("Finish".to_owned())
]
);
let relationship_types = transaction
.query("CALL db.relationshipTypes()", Params::new())
.unwrap();
assert_eq!(relationship_types.columns, ["relationshipType"]);
assert_eq!(
relationship_types.rows[0].values,
[Value::String("CONNECTS".to_owned())]
);
let property_keys = transaction
.query("CALL db.propertyKeys()", Params::new())
.unwrap();
assert_eq!(property_keys.columns, ["propertyKey"]);
assert_eq!(
property_keys
.rows
.iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>(),
[
Value::String("id".to_owned()),
Value::String("name".to_owned())
]
);
let node_schema = transaction
.query("CALL db.schema.nodeTypeProperties()", Params::new())
.unwrap();
assert_eq!(
node_schema.columns,
[
"nodeType",
"nodeLabels",
"propertyName",
"propertyTypes",
"mandatory"
]
);
assert_eq!(node_schema.rows.len(), 3);
assert!(node_schema.rows.iter().any(|row| {
row.values
== [
Value::String(":`Start`".to_owned()),
Value::List(vec![Value::String("Start".to_owned())]),
Value::String("name".to_owned()),
Value::List(vec![Value::String("String".to_owned())]),
Value::Boolean(true),
]
}));
let relationship_schema = transaction
.query("CALL db.schema.relTypeProperties()", Params::new())
.unwrap();
assert_eq!(
relationship_schema.columns,
["relType", "propertyName", "propertyTypes", "mandatory"]
);
assert_eq!(
relationship_schema.rows[0].values,
[
Value::String(":`CONNECTS`".to_owned()),
Value::Null,
Value::Null,
Value::Boolean(false),
]
);
let visualization = transaction
.query("CALL db.schema.visualization()", Params::new())
.unwrap();
assert_eq!(visualization.columns, ["nodes", "relationships"]);
let [Value::List(virtual_nodes), Value::List(virtual_relationships)] =
visualization.rows[0].values.as_slice()
else {
panic!("expected virtual schema graph lists")
};
assert_eq!(virtual_nodes.len(), 2);
assert_eq!(virtual_relationships.len(), 1);
assert!(virtual_nodes.iter().all(|value| {
matches!(value, Value::Node(node)
if node.properties["indexes"] == Value::List(Vec::new())
&& node.properties["constraints"] == Value::List(Vec::new()))
}));
let before_delete = transaction.savepoint().unwrap();
transaction
.query("MATCH (n) DETACH DELETE n", Params::new())
.unwrap();
assert!(transaction
.query("CALL db.labels()", Params::new())
.unwrap()
.rows
.is_empty());
assert!(transaction
.query("CALL db.relationshipTypes()", Params::new())
.unwrap()
.rows
.is_empty());
assert!(transaction
.query("CALL db.schema.nodeTypeProperties()", Params::new())
.unwrap()
.rows
.is_empty());
assert!(transaction
.query("CALL db.schema.relTypeProperties()", Params::new())
.unwrap()
.rows
.is_empty());
assert_eq!(
transaction
.query("CALL db.schema.visualization()", Params::new())
.unwrap()
.rows[0]
.values,
[Value::List(Vec::new()), Value::List(Vec::new())]
);
assert_eq!(
transaction
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.len(),
2
);
transaction.rollback_to(before_delete).unwrap();
transaction.commit().unwrap();
drop(graph);
let mut reopened = Graph::open_neo4j(&database).unwrap();
let ping = reopened.query("CALL db.ping()", Params::new()).unwrap();
assert_eq!(ping.rows[0].values, [Value::Boolean(true)]);
assert_eq!(
reopened
.query("CALL db.info()", Params::new())
.unwrap()
.rows[0],
initial_info.rows[0]
);
assert_eq!(
reopened
.query("CALL db.labels()", Params::new())
.unwrap()
.rows
.len(),
2
);
assert_eq!(
reopened
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.len(),
2
);
assert_eq!(
reopened
.query("CALL db.relationshipTypes()", Params::new())
.unwrap()
.rows[0]
.values,
[Value::String("CONNECTS".to_owned())]
);
}
#[test]
fn database_info_keeps_store_identity_when_the_directory_is_copied() {
fn copy_directory(source: &Path, target: &Path) {
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(source).unwrap() {
let entry = entry.unwrap();
let source_path = entry.path();
let target_path = target.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_directory(&source_path, &target_path);
} else {
std::fs::copy(source_path, target_path).unwrap();
}
}
}
let home = tempfile::tempdir().unwrap();
let source = home.path().join("data/databases/original");
Neo4jStorage::initialize_if_empty(&source).unwrap();
let source_info = {
let mut graph = Graph::open_neo4j(&source).unwrap();
graph
.query("CALL db.info()", Params::new())
.unwrap()
.rows
.remove(0)
};
let copied = home.path().join("data/databases/copied");
copy_directory(&source, &copied);
let copied_info = {
let mut graph = Graph::open_neo4j(&copied).unwrap();
graph
.query("CALL db.info()", Params::new())
.unwrap()
.rows
.remove(0)
};
assert_eq!(source_info.values[0], copied_info.values[0]);
assert_eq!(source_info.values[2], copied_info.values[2]);
assert_eq!(source_info.values[1], Value::String("original".to_owned()));
assert_eq!(copied_info.values[1], Value::String("copied".to_owned()));
}
#[test]
fn token_creation_procedures_follow_transaction_and_reader_semantics() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let result = graph
.query("CALL db.createLabel('Reserved')", Params::new())
.unwrap();
assert!(result.columns.is_empty());
assert!(result.rows.is_empty());
let projected = graph
.query(
"CALL db.createLabel('Projected') RETURN 1 AS value",
Params::new(),
)
.unwrap();
assert_eq!(projected.columns, ["value"]);
assert_eq!(projected.rows[0].values, [Value::Integer(1)]);
graph
.query("CALL db.createLabel('Reserved')", Params::new())
.unwrap();
graph
.query(
"CALL db.createRelationshipType('RESERVED_FOR')",
Params::new(),
)
.unwrap();
graph
.query(
"CALL db.createProperty($name)",
Params::from([("name".to_owned(), Value::String("reservedKey".to_owned()))]),
)
.unwrap();
assert!(graph
.query("CALL db.labels()", Params::new())
.unwrap()
.rows
.is_empty());
assert!(graph
.query("CALL db.relationshipTypes()", Params::new())
.unwrap()
.rows
.is_empty());
assert_eq!(
graph
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows[0]
.values,
[Value::String("reservedKey".to_owned())]
);
let mut transaction = graph.transaction().unwrap();
let before_tokens = transaction.savepoint().unwrap();
transaction
.query("CALL db.createProperty('rolledBackKey')", Params::new())
.unwrap();
assert_eq!(
transaction
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.len(),
2
);
transaction.rollback_to(before_tokens).unwrap();
assert_eq!(
transaction
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.len(),
1
);
transaction.commit().unwrap();
drop(graph);
let mut reopened = Graph::open_neo4j(&database).unwrap();
assert_eq!(
reopened
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.len(),
1
);
assert!(matches!(
reopened.query("CALL db.createProperty('denied')", Params::new()),
Err(Error::UnsupportedWriteQuery(_))
| Err(Error::Transaction(TransactionErrorKind::NotActive))
));
}
#[test]
fn write_procedures_execute_once_per_input_row() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let batch = graph
.query(
"UNWIND ['batchOne', 'batchTwo'] AS name \
CALL db.createProperty(name) RETURN name",
Params::new(),
)
.unwrap();
assert_eq!(batch.columns, ["name"]);
assert_eq!(
batch
.rows
.iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>(),
[
Value::String("batchOne".to_owned()),
Value::String("batchTwo".to_owned()),
]
);
graph
.query("CREATE (:TokenSource {name: 'fromMatch'})", Params::new())
.unwrap();
let matched = graph
.query(
"MATCH (source:TokenSource) CALL db.createProperty(source.name) \
RETURN source.name",
Params::new(),
)
.unwrap();
assert_eq!(
matched.rows[0].values,
[Value::String("fromMatch".to_owned())]
);
let empty = graph
.query(
"UNWIND [] AS name CALL db.createProperty('emptyInput') RETURN name",
Params::new(),
)
.unwrap();
assert!(empty.rows.is_empty());
let property_keys = graph
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.into_iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>();
for expected in ["batchOne", "batchTwo", "name", "fromMatch"] {
assert!(property_keys.contains(&Value::String(expected.to_owned())));
}
assert!(!property_keys.contains(&Value::String("emptyInput".to_owned())));
let mut transaction = graph.transaction().unwrap();
transaction
.query(
"UNWIND ['rollbackOne', 'rollbackTwo'] AS name \
CALL db.createProperty(name) RETURN name",
Params::new(),
)
.unwrap();
transaction.rollback().unwrap();
let property_keys = graph
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.into_iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>();
assert!(!property_keys.contains(&Value::String("rollbackOne".to_owned())));
assert!(!property_keys.contains(&Value::String("rollbackTwo".to_owned())));
}
#[test]
fn read_only_transaction_options_reject_writes() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
{
let mut transaction = graph
.transaction_with_options(TransactionOptions {
read_only: true,
..TransactionOptions::default()
})
.unwrap();
assert_eq!(
transaction.query("RETURN 1", Params::new()).unwrap().rows[0].values,
[Value::Integer(1)]
);
assert!(matches!(
transaction.query("CREATE (:ReadOnlyDenied)", Params::new()),
Err(Error::AccessMode)
));
}
let result = graph
.query("MATCH (n:ReadOnlyDenied) RETURN n", Params::new())
.unwrap();
assert!(result.rows.is_empty());
}
#[test]
fn write_procedures_execute_after_supported_with_scopes() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let first_scope = graph
.query(
"UNWIND ['afterWithOne', 'afterWithTwo'] AS name WITH name \
CALL db.createProperty(name) RETURN name",
Params::new(),
)
.unwrap();
assert_eq!(first_scope.rows.len(), 2);
let second_scope = graph
.query(
"UNWIND ['afterSecondWith'] AS name WITH name WITH name \
CALL db.createProperty(name) RETURN name",
Params::new(),
)
.unwrap();
assert_eq!(second_scope.rows.len(), 1);
let mut transaction = graph.transaction().unwrap();
transaction
.query(
"UNWIND ['lateRollbackOne', 'lateRollbackTwo'] AS name WITH name \
CALL db.createProperty(name) RETURN name",
Params::new(),
)
.unwrap();
transaction.rollback().unwrap();
for query in [
"CALL db.ping() YIELD success WITH success \
CALL db.createProperty('mixedMode') RETURN success",
"CALL db.createProperty('firstStage') WITH 1 AS n \
CALL db.createProperty('secondStage') RETURN n",
] {
assert!(matches!(
graph.query(query, Params::new()),
Err(Error::Validation(_))
));
}
let property_keys = graph
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.into_iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>();
for expected in ["afterWithOne", "afterWithTwo", "afterSecondWith"] {
assert!(property_keys.contains(&Value::String(expected.to_owned())));
}
for absent in [
"lateRollbackOne",
"lateRollbackTwo",
"mixedMode",
"firstStage",
"secondStage",
] {
assert!(!property_keys.contains(&Value::String(absent.to_owned())));
}
}
#[test]
fn token_creation_procedures_validate_arguments_without_committing_artifacts() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
for query in [
"CALL db.createProperty()",
"CALL db.createProperty(null)",
"CALL db.createProperty(1)",
"CALL db.createProperty('')",
] {
assert!(graph.query(query, Params::new()).is_err(), "{query}");
}
assert!(graph
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.is_empty());
}
#[test]
fn concurrent_token_procedures_use_existing_mvcc_conflict_rules() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut first_graph = Graph::open_neo4j_writable(&database).unwrap();
let mut second_graph = Graph::open_neo4j_writable(&database).unwrap();
let mut first = first_graph.transaction().unwrap();
let mut second = second_graph.transaction().unwrap();
first
.query("CALL db.createProperty('firstKey')", Params::new())
.unwrap();
second
.query("CALL db.createProperty('secondKey')", Params::new())
.unwrap();
first.commit().unwrap();
assert!(matches!(
second.commit(),
Err(Error::Transaction(TransactionErrorKind::Conflict))
));
let mut third = first_graph.transaction().unwrap();
let mut fourth = second_graph.transaction().unwrap();
third
.query("CALL db.createLabel('ConcurrentLabel')", Params::new())
.unwrap();
fourth
.query("CALL db.createProperty('disjointKey')", Params::new())
.unwrap();
third.commit().unwrap();
fourth.commit().unwrap();
drop(first_graph);
drop(second_graph);
let mut reopened = Graph::open_neo4j(&database).unwrap();
let keys = reopened
.query("CALL db.propertyKeys()", Params::new())
.unwrap();
assert_eq!(
keys.rows
.into_iter()
.map(|row| row.values[0].clone())
.collect::<Vec<_>>(),
[
Value::String("firstKey".to_owned()),
Value::String("disjointKey".to_owned())
]
);
}
#[test]
fn token_procedure_commit_failure_leaves_no_artifacts() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
crate::neo4j_storage::fail_next_commit_after_patch(0);
assert!(graph
.query("CALL db.createProperty('notCommitted')", Params::new())
.is_err());
drop(graph);
assert!(!database.join(".littlegraph-write-journal").exists());
let mut reopened = Graph::open_neo4j(&database).unwrap();
assert!(reopened
.query("CALL db.propertyKeys()", Params::new())
.unwrap()
.rows
.is_empty());
}
#[test]
fn api_comparison_scans_propagate_cancellation() {
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
let values = (0..QUERY_CONTROL_COMPARISON_BATCH * 3).collect::<Vec<_>>();
assert!(matches!(
controlled_position(&storage, &values, |value| *value == usize::MAX),
Err(Error::Transaction(TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
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(),
);
assert!(matches!(
evaluate_write_in_predicate(list, Value::Integer(-1), Some(&storage)),
Err(Error::Transaction(TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 1,
};
let mut rows = vec![Record {
values: vec![Value::Integer(1)],
}];
assert!(matches!(
deduplicate_rows(&storage, &mut rows),
Err(Error::Transaction(TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 2,
};
assert!(matches!(
evaluate_write_range_value(
Value::Integer(1),
Value::Integer(1_000_000),
None,
Some(&storage),
),
Err(Error::Transaction(TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
let storage = CancellingStorage {
checks: Cell::new(0),
cancel_at: 1,
};
let item = ReturnItem {
expression: ReturnExpression::Scalar(Expression::Literal(Value::Integer(1))),
alias: None,
};
assert!(matches!(
project_created_item(&storage, 0, None, &item, &Params::new()),
Err(Error::Transaction(TransactionErrorKind::Cancelled))
));
assert_eq!(storage.checks.get(), storage.cancel_at);
}
#[test]
fn retry_helper_does_not_retry_cancellation_or_execution_errors() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let token = CancellationToken::new();
token.cancel();
let attempts = Cell::new(0);
let error = graph
.run_transaction_with_options(
TransactionOptions {
cancellation_token: Some(token),
..TransactionOptions::default()
},
3,
|transaction| {
attempts.set(attempts.get() + 1);
transaction.query("MATCH (n) RETURN n", Params::new())?;
Ok(())
},
)
.unwrap_err();
assert!(matches!(
error,
Error::Transaction(TransactionErrorKind::Cancelled)
));
assert_eq!(attempts.get(), 1);
let attempts = Cell::new(0);
let error = graph
.run_transaction(3, |transaction| {
attempts.set(attempts.get() + 1);
transaction.query("THIS IS NOT CYPHER", Params::new())?;
Ok(())
})
.unwrap_err();
assert!(matches!(error, Error::Parse(_)));
assert_eq!(attempts.get(), 1);
}
#[test]
fn workspace_limits_accept_exact_boundaries_and_charge_savepoints() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let (base_usage, usage, savepoint_usage) = {
let mut transaction = graph.transaction().unwrap();
let base_usage = transaction.graph.backend.workspace_usage().unwrap();
transaction
.query("CREATE (:BudgetBoundary {value: 1})", Params::new())
.unwrap();
let usage = transaction.graph.backend.workspace_usage().unwrap();
let savepoint_usage = transaction.savepoint_usage().unwrap();
transaction.rollback().unwrap();
(base_usage, usage, savepoint_usage)
};
assert!(base_usage.bytes > 0);
assert_eq!(base_usage.records, 0);
assert!(usage.bytes > 0);
assert!(usage.records > 0);
graph
.transaction_with_options(TransactionOptions {
max_workspace_bytes: Some(base_usage.bytes),
..TransactionOptions::default()
})
.unwrap()
.commit()
.unwrap();
assert!(matches!(
graph.transaction_with_options(TransactionOptions {
max_workspace_bytes: Some(base_usage.bytes - 1),
..TransactionOptions::default()
}),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
{
let mut transaction = graph
.transaction_with_options(TransactionOptions {
max_workspace_bytes: Some(usage.bytes),
max_records: Some(usage.records),
..TransactionOptions::default()
})
.unwrap();
transaction
.query("CREATE (:BudgetBoundary {value: 1})", Params::new())
.unwrap();
transaction.rollback().unwrap();
}
for options in [
TransactionOptions {
max_workspace_bytes: Some(usage.bytes - 1),
..TransactionOptions::default()
},
TransactionOptions {
max_records: Some(usage.records - 1),
..TransactionOptions::default()
},
] {
let mut transaction = graph.transaction_with_options(options).unwrap();
assert!(matches!(
transaction.query("CREATE (:BudgetBoundary {value: 1})", Params::new()),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
transaction.rollback().unwrap();
}
let savepoint_limit = usage.checked_add(savepoint_usage).unwrap();
let mut transaction = graph
.transaction_with_options(TransactionOptions {
max_workspace_bytes: Some(savepoint_limit.bytes),
max_records: Some(savepoint_limit.records),
..TransactionOptions::default()
})
.unwrap();
transaction
.query("CREATE (:BudgetBoundary {value: 1})", Params::new())
.unwrap();
let _ = transaction.savepoint().unwrap();
assert!(matches!(
transaction.savepoint(),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
transaction.rollback().unwrap();
}
#[test]
fn retained_savepoints_reduce_per_mutation_workspace_limit() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
let (one_node_usage, savepoint_usage) = {
let transaction = graph.transaction().unwrap();
let savepoint_usage = transaction.savepoint_usage().unwrap();
transaction
.graph
.write_storage()
.unwrap()
.create_node(Vec::new(), Properties::new())
.unwrap();
let one_node_usage = transaction.graph.backend.workspace_usage().unwrap();
transaction.rollback().unwrap();
(one_node_usage, savepoint_usage)
};
let limit = one_node_usage.checked_add(savepoint_usage).unwrap();
let mut transaction = graph
.transaction_with_options(TransactionOptions {
max_workspace_bytes: Some(limit.bytes),
..TransactionOptions::default()
})
.unwrap();
let _ = transaction.savepoint().unwrap();
transaction
.graph
.write_storage()
.unwrap()
.create_node(Vec::new(), Properties::new())
.unwrap();
assert!(matches!(
transaction
.graph
.write_storage()
.unwrap()
.create_node(Vec::new(), Properties::new()),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
transaction.rollback().unwrap();
}
#[test]
fn savepoint_rollback_does_not_clear_deadline_or_cancellation() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j_writable(&database).unwrap();
{
let mut transaction = graph.transaction().unwrap();
let savepoint = transaction.savepoint().unwrap();
transaction.deadline = Some(Instant::now());
assert!(matches!(
transaction.query("MATCH (n) RETURN n", Params::new()),
Err(Error::Transaction(TransactionErrorKind::TimedOut))
));
transaction.rollback_to(savepoint).unwrap();
assert!(matches!(
transaction.query("MATCH (n) RETURN n", Params::new()),
Err(Error::Transaction(TransactionErrorKind::TimedOut))
));
transaction.rollback().unwrap();
}
{
let token = CancellationToken::new();
let mut transaction = graph
.transaction_with_options(TransactionOptions {
cancellation_token: Some(token.clone()),
..TransactionOptions::default()
})
.unwrap();
let savepoint = transaction.savepoint().unwrap();
token.cancel();
assert!(matches!(
transaction.query("MATCH (n) RETURN n", Params::new()),
Err(Error::Transaction(TransactionErrorKind::Cancelled))
));
transaction.rollback_to(savepoint).unwrap();
assert!(matches!(
transaction.query("MATCH (n) RETURN n", Params::new()),
Err(Error::Transaction(TransactionErrorKind::Cancelled))
));
transaction.rollback().unwrap();
}
}
#[test]
fn read_only_savepoints_charge_their_handle_state() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j(&database).unwrap();
let savepoint_bytes = std::mem::size_of::<TransactionSavepoint>();
{
let mut transaction = graph
.transaction_with_options(TransactionOptions {
max_workspace_bytes: Some(savepoint_bytes),
..TransactionOptions::default()
})
.unwrap();
let _ = transaction.savepoint().unwrap();
assert!(matches!(
transaction.savepoint(),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
transaction.rollback().unwrap();
}
let mut transaction = graph
.transaction_with_options(TransactionOptions {
max_workspace_bytes: Some(savepoint_bytes - 1),
..TransactionOptions::default()
})
.unwrap();
assert!(matches!(
transaction.savepoint(),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
transaction.rollback().unwrap();
}
#[test]
fn procedure_materialization_obeys_the_query_memory_limit() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j(&database).unwrap();
assert_eq!(
graph
.query("CALL db.schema.visualization()", Params::new())
.unwrap()
.rows
.len(),
1
);
let mut transaction = graph
.transaction_with_options(TransactionOptions {
max_query_memory_bytes: Some(0),
..TransactionOptions::default()
})
.unwrap();
assert!(matches!(
transaction.query("CALL db.schema.visualization()", Params::new()),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
assert!(matches!(
transaction.query("CALL db.ping()", Params::new()),
Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
));
transaction.rollback().unwrap();
}
#[test]
fn controlled_executor_propagates_deadlines_and_clears_control_state() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let mut graph = Graph::open_neo4j(&database).unwrap();
let statement = parse_statement("MATCH (n) RETURN n").unwrap();
assert!(matches!(
graph.execute_controlled_statement(
statement,
&Params::new(),
QueryControl {
deadline: Some(Instant::now()),
cancellation_token: None,
max_query_memory_bytes: None,
query_memory_bytes: Cell::new(0),
},
),
Err(Error::Transaction(TransactionErrorKind::TimedOut))
));
assert!(graph.query_control.is_none());
assert!(graph
.query("MATCH (n) RETURN n", Params::new())
.unwrap()
.rows
.is_empty());
}
#[test]
fn controlled_write_range_observes_deadline() {
let home = tempfile::tempdir().unwrap();
let database = home.path().join("data/databases/neo4j");
Neo4jStorage::initialize_if_empty(&database).unwrap();
let graph = Graph::open_neo4j(&database).unwrap();
let control = QueryControl {
deadline: Some(Instant::now()),
cancellation_token: None,
max_query_memory_bytes: None,
query_memory_bytes: Cell::new(0),
};
let storage = ControlledStorage {
storage: graph.backend.read(),
control: Some(&control),
};
assert!(matches!(
evaluate_write_range_value(
Value::Integer(1),
Value::Integer(1_000_000),
None,
Some(&storage),
),
Err(Error::Transaction(TransactionErrorKind::TimedOut))
));
}
}
fn find_merge_node(
storage: &dyn StorageInterface,
pattern: &NodePattern,
properties: &Properties,
) -> Result<Option<NodeId>> {
for node_id in storage.node_ids() {
storage.check_query_control()?;
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution(format!("missing node id {node_id}")))?;
let mut labels_match = true;
for label in &pattern.labels {
if controlled_position(storage, &node.labels, |node_label| node_label == label)?
.is_none()
{
labels_match = false;
break;
}
}
if labels_match
&& properties
.iter()
.all(|(key, value)| node.properties.get(key) == Some(value))
{
return Ok(Some(node_id));
}
}
Ok(None)
}
fn find_merge_relationship(
storage: &dyn StorageInterface,
start: NodeId,
end: NodeId,
direction: Direction,
relationship_types: &[String],
properties: &Properties,
) -> Result<Option<RelationshipId>> {
for relationship_id in storage.outgoing_relationships(start) {
storage.check_query_control()?;
let relationship = storage.relationship(*relationship_id).ok_or_else(|| {
Error::Execution(format!("missing relationship id {relationship_id}"))
})?;
if relationship.end == end
&& relationship_matches_merge_properties(
storage,
relationship,
relationship_types,
properties,
)?
{
return Ok(Some(*relationship_id));
}
}
if direction == Direction::Undirected {
for relationship_id in storage.incoming_relationships(start) {
storage.check_query_control()?;
let relationship = storage.relationship(*relationship_id).ok_or_else(|| {
Error::Execution(format!("missing relationship id {relationship_id}"))
})?;
if relationship.start == end
&& relationship_matches_merge_properties(
storage,
relationship,
relationship_types,
properties,
)?
{
return Ok(Some(*relationship_id));
}
}
}
Ok(None)
}
fn set_item_variable(item: &SetItem) -> String {
match item {
SetItem::Property { variable, .. }
| SetItem::PropertiesMerge { variable, .. }
| SetItem::PropertiesReplace { variable, .. }
| SetItem::Label { variable, .. } => variable.clone(),
}
}
fn collect_expression_variables(expression: &Expression) -> BTreeSet<String> {
let mut variables = BTreeSet::new();
collect_expression_variables_inner(expression, &mut variables);
variables
}
fn collect_set_item_variables(item: &SetItem) -> BTreeSet<String> {
match item {
SetItem::Property { expression, .. }
| SetItem::PropertiesMerge { expression, .. }
| SetItem::PropertiesReplace { expression, .. } => collect_expression_variables(expression),
SetItem::Label { .. } => BTreeSet::new(),
}
}
fn collect_expression_variables_inner(expression: &Expression, variables: &mut BTreeSet<String>) {
match expression {
Expression::Literal(_) | Expression::Parameter(_) | Expression::Pi | Expression::E => {}
Expression::Operand(operand) => collect_operand_variables(operand, variables),
Expression::Add(left, right)
| Expression::Subtract(left, right)
| Expression::Multiply(left, right)
| Expression::Divide(left, right)
| Expression::Modulo(left, right) => {
collect_expression_variables_inner(left, variables);
collect_expression_variables_inner(right, variables);
}
Expression::List(items) | Expression::Coalesce(items) => {
for item in items {
collect_expression_variables_inner(item, variables);
}
}
Expression::Map(entries) => {
for value in entries.values() {
collect_expression_variables_inner(value, variables);
}
}
Expression::MapProjection {
variable: projection_variable,
items,
} => {
variables.insert(projection_variable.clone());
for item in items {
if let crate::cypher::ast::MapProjectionItem::Expression { expression, .. } = item {
collect_expression_variables_inner(expression, variables);
}
}
}
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)
| Expression::Reverse(expression)
| Expression::Abs(expression)
| Expression::Sign(expression)
| Expression::Sqrt(expression)
| Expression::Round(expression)
| Expression::Log(expression)
| Expression::Log10(expression)
| Expression::Exp(expression)
| Expression::Haversin(expression) => {
collect_expression_variables_inner(expression, variables)
}
Expression::Range { start, end, step } => {
collect_expression_variables_inner(start, variables);
collect_expression_variables_inner(end, variables);
if let Some(step) = step {
collect_expression_variables_inner(step, variables);
}
}
Expression::ListIndex { value, index } => {
collect_expression_variables_inner(value, variables);
collect_expression_variables_inner(index, variables);
}
Expression::ListSlice { value, start, end } => {
collect_expression_variables_inner(value, variables);
if let Some(start) = start {
collect_expression_variables_inner(start, variables);
}
if let Some(end) = end {
collect_expression_variables_inner(end, variables);
}
}
Expression::Substring {
value,
start,
length,
} => {
collect_expression_variables_inner(value, variables);
collect_expression_variables_inner(start, variables);
if let Some(length) = length {
collect_expression_variables_inner(length, variables);
}
}
Expression::Replace {
value,
search,
replacement,
} => {
collect_expression_variables_inner(value, variables);
collect_expression_variables_inner(search, variables);
collect_expression_variables_inner(replacement, variables);
}
Expression::Trim { expression, .. }
| Expression::StringSlice {
value: expression, ..
}
| Expression::Rounding { expression, .. }
| Expression::AngleConversion { expression, .. }
| Expression::Trigonometric { expression, .. }
| Expression::InverseTrigonometric { expression, .. } => {
collect_expression_variables_inner(expression, variables)
}
Expression::Split { value, delimiter } => {
collect_expression_variables_inner(value, variables);
collect_expression_variables_inner(delimiter, variables);
}
Expression::Atan2 { y, x } => {
collect_expression_variables_inner(y, variables);
collect_expression_variables_inner(x, variables);
}
Expression::ListPredicate {
variable,
list,
predicate,
..
} => {
collect_expression_variables_inner(list, variables);
let mut nested = BTreeSet::new();
collect_predicate_variables(predicate, &mut nested);
nested.remove(variable);
variables.extend(nested);
}
Expression::ListComprehension {
variable,
list,
predicate,
projection,
} => {
collect_expression_variables_inner(list, variables);
let mut nested = BTreeSet::new();
if let Some(predicate) = predicate {
collect_predicate_variables(predicate, &mut nested);
}
collect_expression_variables_inner(projection, &mut nested);
nested.remove(variable);
variables.extend(nested);
}
Expression::PatternComprehension {
pattern,
predicate,
projection,
} => {
let mut pattern_variables = Vec::new();
collect_pattern_entity_variables(pattern, &mut pattern_variables);
variables.extend(pattern_variables);
if let Some(predicate) = predicate {
collect_predicate_variables(predicate, variables);
}
collect_expression_variables_inner(projection, variables);
}
Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => {
collect_expression_variables_inner(initial, variables);
collect_expression_variables_inner(list, variables);
let mut nested = BTreeSet::new();
collect_expression_variables_inner(expression, &mut nested);
nested.remove(accumulator);
nested.remove(variable);
variables.extend(nested);
}
Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
collect_predicate_variables(&alternative.predicate, variables);
collect_expression_variables_inner(&alternative.expression, variables);
}
collect_expression_variables_inner(else_expression, variables);
}
Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
collect_expression_variables_inner(operand, variables);
for alternative in alternatives {
collect_expression_variables_inner(&alternative.value, variables);
collect_expression_variables_inner(&alternative.expression, variables);
}
collect_expression_variables_inner(else_expression, variables);
}
Expression::Predicate(predicate) => collect_predicate_variables(predicate, variables),
}
}
fn collect_predicate_variables(predicate: &Predicate, variables: &mut BTreeSet<String>) {
match predicate {
Predicate::Comparison { left, right, .. } => {
collect_expression_variables_inner(left, variables);
collect_expression_variables_inner(right, variables);
}
Predicate::StringMatch { left, right, .. } => {
collect_expression_variables_inner(left, variables);
collect_expression_variables_inner(right, variables);
}
Predicate::In { item, list } => {
collect_expression_variables_inner(item, variables);
collect_expression_variables_inner(list, variables);
}
Predicate::And(left, right) | Predicate::Or(left, right) | Predicate::Xor(left, right) => {
collect_predicate_variables(left, variables);
collect_predicate_variables(right, variables);
}
Predicate::Not(inner) => collect_predicate_variables(inner, variables),
Predicate::Pattern(pattern) => {
if let Some(variable) = &pattern.start.variable {
variables.insert(variable.clone());
}
for chain in &pattern.chains {
if let Some(variable) = &chain.node.variable {
variables.insert(variable.clone());
}
}
}
Predicate::IsNull(expression) | Predicate::IsNotNull(expression) => {
collect_expression_variables_inner(expression, variables)
}
Predicate::Boolean(expression) => collect_expression_variables_inner(expression, variables),
Predicate::Exists(operand) => collect_operand_variables(operand, variables),
Predicate::ExistsSubquery(matches) => {
for clause in matches {
for pattern in &clause.patterns {
collect_pattern_variables(pattern, variables);
}
if let Some(predicate) = &clause.predicate {
collect_predicate_variables(predicate, variables);
}
}
}
}
}
fn collect_pattern_variables(
pattern: &crate::cypher::ast::Pattern,
variables: &mut BTreeSet<String>,
) {
if let Some(variable) = &pattern.start.variable {
variables.insert(variable.clone());
}
for chain in &pattern.chains {
if let Some(variable) = &chain.relationship.variable {
variables.insert(variable.clone());
}
if let Some(variable) = &chain.node.variable {
variables.insert(variable.clone());
}
}
}
fn collect_operand_variables(operand: &Operand, variables: &mut BTreeSet<String>) {
match operand {
Operand::Variable(variable) => {
variables.insert(variable.clone());
}
Operand::Property { variable, .. } => {
variables.insert(variable.clone());
}
Operand::DynamicProperty { variable, key } => {
variables.insert(variable.clone());
collect_expression_variables_inner(key, variables);
}
Operand::Literal(_) | Operand::Parameter(_) => {}
}
}
fn substitute_set_item_value(item: &SetItem, variable: &str, value: &Value) -> SetItem {
match item {
SetItem::Property {
variable: item_variable,
key,
expression,
} => SetItem::Property {
variable: item_variable.clone(),
key: key.clone(),
expression: substitute_expression_value(expression, variable, value),
},
SetItem::PropertiesMerge {
variable: item_variable,
expression,
} => SetItem::PropertiesMerge {
variable: item_variable.clone(),
expression: substitute_expression_value(expression, variable, value),
},
SetItem::PropertiesReplace {
variable: item_variable,
expression,
} => SetItem::PropertiesReplace {
variable: item_variable.clone(),
expression: substitute_expression_value(expression, variable, value),
},
SetItem::Label {
variable: item_variable,
labels,
} => SetItem::Label {
variable: item_variable.clone(),
labels: labels.clone(),
},
}
}
fn substitute_expression_value(
expression: &Expression,
variable: &str,
value: &Value,
) -> Expression {
match expression {
Expression::Literal(_) | Expression::Parameter(_) | Expression::Pi | Expression::E => {
expression.clone()
}
Expression::Operand(operand) => {
Expression::Operand(substitute_operand_value(operand, variable, value))
}
Expression::Add(left, right) => Expression::Add(
Box::new(substitute_expression_value(left, variable, value)),
Box::new(substitute_expression_value(right, variable, value)),
),
Expression::Subtract(left, right) => Expression::Subtract(
Box::new(substitute_expression_value(left, variable, value)),
Box::new(substitute_expression_value(right, variable, value)),
),
Expression::Multiply(left, right) => Expression::Multiply(
Box::new(substitute_expression_value(left, variable, value)),
Box::new(substitute_expression_value(right, variable, value)),
),
Expression::Divide(left, right) => Expression::Divide(
Box::new(substitute_expression_value(left, variable, value)),
Box::new(substitute_expression_value(right, variable, value)),
),
Expression::Modulo(left, right) => Expression::Modulo(
Box::new(substitute_expression_value(left, variable, value)),
Box::new(substitute_expression_value(right, variable, value)),
),
Expression::List(items) => Expression::List(
items
.iter()
.map(|item| substitute_expression_value(item, variable, value))
.collect(),
),
Expression::Map(entries) => Expression::Map(
entries
.iter()
.map(|(key, expression)| {
(
key.clone(),
substitute_expression_value(expression, variable, value),
)
})
.collect(),
),
Expression::MapProjection {
variable: projection_variable,
items,
} => Expression::MapProjection {
variable: projection_variable.clone(),
items: items
.iter()
.map(|item| match item {
crate::cypher::ast::MapProjectionItem::AllProperties => {
crate::cypher::ast::MapProjectionItem::AllProperties
}
crate::cypher::ast::MapProjectionItem::Property(key) => {
crate::cypher::ast::MapProjectionItem::Property(key.clone())
}
crate::cypher::ast::MapProjectionItem::Variable(variable) => {
crate::cypher::ast::MapProjectionItem::Variable(variable.clone())
}
crate::cypher::ast::MapProjectionItem::Expression { key, expression } => {
crate::cypher::ast::MapProjectionItem::Expression {
key: key.clone(),
expression: substitute_expression_value(expression, variable, value),
}
}
})
.collect(),
},
Expression::Coalesce(items) => Expression::Coalesce(
items
.iter()
.map(|item| substitute_expression_value(item, variable, value))
.collect(),
),
Expression::ToLower(expression) => Expression::ToLower(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToUpper(expression) => Expression::ToUpper(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToString(expression) => Expression::ToString(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToInteger(expression) => Expression::ToInteger(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToFloat(expression) => Expression::ToFloat(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToBoolean(expression) => Expression::ToBoolean(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToStringOrNull(expression) => Expression::ToStringOrNull(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToIntegerOrNull(expression) => Expression::ToIntegerOrNull(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToFloatOrNull(expression) => Expression::ToFloatOrNull(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ToBooleanOrNull(expression) => Expression::ToBooleanOrNull(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::IsEmpty(expression) => Expression::IsEmpty(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::Head(expression) => Expression::Head(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Last(expression) => Expression::Last(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Tail(expression) => Expression::Tail(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Range { start, end, step } => Expression::Range {
start: Box::new(substitute_expression_value(start, variable, value)),
end: Box::new(substitute_expression_value(end, variable, value)),
step: step
.as_ref()
.map(|step| Box::new(substitute_expression_value(step, variable, value))),
},
Expression::ListIndex {
value: list_value,
index,
} => Expression::ListIndex {
value: Box::new(substitute_expression_value(list_value, variable, value)),
index: Box::new(substitute_expression_value(index, variable, value)),
},
Expression::ListSlice {
value: list_value,
start,
end,
} => Expression::ListSlice {
value: Box::new(substitute_expression_value(list_value, variable, value)),
start: start
.as_ref()
.map(|start| Box::new(substitute_expression_value(start, variable, value))),
end: end
.as_ref()
.map(|end| Box::new(substitute_expression_value(end, variable, value))),
},
Expression::Size(expression) => Expression::Size(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Substring {
value: inner,
start,
length,
} => Expression::Substring {
value: Box::new(substitute_expression_value(inner, variable, value)),
start: Box::new(substitute_expression_value(start, variable, value)),
length: length
.as_ref()
.map(|length| Box::new(substitute_expression_value(length, variable, value))),
},
Expression::Replace {
value: inner,
search,
replacement,
} => Expression::Replace {
value: Box::new(substitute_expression_value(inner, variable, value)),
search: Box::new(substitute_expression_value(search, variable, value)),
replacement: Box::new(substitute_expression_value(replacement, variable, value)),
},
Expression::Trim { mode, expression } => Expression::Trim {
mode: mode.clone(),
expression: Box::new(substitute_expression_value(expression, variable, value)),
},
Expression::Split {
value: inner,
delimiter,
} => Expression::Split {
value: Box::new(substitute_expression_value(inner, variable, value)),
delimiter: Box::new(substitute_expression_value(delimiter, variable, value)),
},
Expression::StringSlice {
mode,
value: inner,
length,
} => Expression::StringSlice {
mode: mode.clone(),
value: Box::new(substitute_expression_value(inner, variable, value)),
length: Box::new(substitute_expression_value(length, variable, value)),
},
Expression::Reverse(expression) => Expression::Reverse(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::Abs(expression) => Expression::Abs(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Rounding { mode, expression } => Expression::Rounding {
mode: mode.clone(),
expression: Box::new(substitute_expression_value(expression, variable, value)),
},
Expression::Sign(expression) => Expression::Sign(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Sqrt(expression) => Expression::Sqrt(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Round(expression) => Expression::Round(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Log(expression) => Expression::Log(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Log10(expression) => Expression::Log10(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::Exp(expression) => Expression::Exp(Box::new(substitute_expression_value(
expression, variable, value,
))),
Expression::AngleConversion { mode, expression } => Expression::AngleConversion {
mode: mode.clone(),
expression: Box::new(substitute_expression_value(expression, variable, value)),
},
Expression::Trigonometric { mode, expression } => Expression::Trigonometric {
mode: mode.clone(),
expression: Box::new(substitute_expression_value(expression, variable, value)),
},
Expression::InverseTrigonometric { mode, expression } => Expression::InverseTrigonometric {
mode: mode.clone(),
expression: Box::new(substitute_expression_value(expression, variable, value)),
},
Expression::Atan2 { y, x } => Expression::Atan2 {
y: Box::new(substitute_expression_value(y, variable, value)),
x: Box::new(substitute_expression_value(x, variable, value)),
},
Expression::Haversin(expression) => Expression::Haversin(Box::new(
substitute_expression_value(expression, variable, value),
)),
Expression::ListPredicate {
mode,
variable: inner,
list,
predicate,
} => {
if inner == variable {
expression.clone()
} else {
Expression::ListPredicate {
mode: *mode,
variable: inner.clone(),
list: Box::new(substitute_expression_value(list, variable, value)),
predicate: Box::new(substitute_predicate_value(predicate, variable, value)),
}
}
}
Expression::ListComprehension {
variable: inner,
list,
predicate,
projection,
} => {
if inner == variable {
expression.clone()
} else {
Expression::ListComprehension {
variable: inner.clone(),
list: Box::new(substitute_expression_value(list, variable, value)),
predicate: predicate.as_ref().map(|predicate| {
Box::new(substitute_predicate_value(predicate, variable, value))
}),
projection: Box::new(substitute_expression_value(projection, variable, value)),
}
}
}
Expression::PatternComprehension {
pattern,
predicate,
projection,
} => Expression::PatternComprehension {
pattern: pattern.clone(),
predicate: predicate
.as_ref()
.map(|predicate| Box::new(substitute_predicate_value(predicate, variable, value))),
projection: Box::new(substitute_expression_value(projection, variable, value)),
},
Expression::Reduce {
accumulator,
initial,
variable: inner,
list,
expression: reduce_expression,
} => {
let initial = Box::new(substitute_expression_value(initial, variable, value));
let list = Box::new(substitute_expression_value(list, variable, value));
if accumulator == variable || inner == variable {
Expression::Reduce {
accumulator: accumulator.clone(),
initial,
variable: inner.clone(),
list,
expression: reduce_expression.clone(),
}
} else {
Expression::Reduce {
accumulator: accumulator.clone(),
initial,
variable: inner.clone(),
list,
expression: Box::new(substitute_expression_value(
reduce_expression,
variable,
value,
)),
}
}
}
Expression::Case {
alternatives,
else_expression,
} => Expression::Case {
alternatives: alternatives
.iter()
.map(|alternative| crate::cypher::ast::CaseAlternative {
predicate: substitute_predicate_value(&alternative.predicate, variable, value),
expression: substitute_expression_value(
&alternative.expression,
variable,
value,
),
})
.collect(),
else_expression: Box::new(substitute_expression_value(
else_expression,
variable,
value,
)),
},
Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => Expression::SimpleCase {
operand: Box::new(substitute_expression_value(operand, variable, value)),
alternatives: alternatives
.iter()
.map(|alternative| crate::cypher::ast::SimpleCaseAlternative {
value: substitute_expression_value(&alternative.value, variable, value),
expression: substitute_expression_value(
&alternative.expression,
variable,
value,
),
})
.collect(),
else_expression: Box::new(substitute_expression_value(
else_expression,
variable,
value,
)),
},
Expression::Predicate(predicate) => Expression::Predicate(Box::new(
substitute_predicate_value(predicate, variable, value),
)),
}
}
fn substitute_predicate_value(predicate: &Predicate, variable: &str, value: &Value) -> Predicate {
match predicate {
Predicate::Comparison {
left,
operator,
right,
} => Predicate::Comparison {
left: substitute_expression_value(left, variable, value),
operator: *operator,
right: substitute_expression_value(right, variable, value),
},
Predicate::In { item, list } => Predicate::In {
item: substitute_expression_value(item, variable, value),
list: substitute_expression_value(list, variable, value),
},
Predicate::StringMatch {
left,
operator,
right,
} => Predicate::StringMatch {
left: substitute_expression_value(left, variable, value),
operator: *operator,
right: substitute_expression_value(right, variable, value),
},
Predicate::And(left, right) => Predicate::And(
Box::new(substitute_predicate_value(left, variable, value)),
Box::new(substitute_predicate_value(right, variable, value)),
),
Predicate::Or(left, right) => Predicate::Or(
Box::new(substitute_predicate_value(left, variable, value)),
Box::new(substitute_predicate_value(right, variable, value)),
),
Predicate::Xor(left, right) => Predicate::Xor(
Box::new(substitute_predicate_value(left, variable, value)),
Box::new(substitute_predicate_value(right, variable, value)),
),
Predicate::Not(inner) => {
Predicate::Not(Box::new(substitute_predicate_value(inner, variable, value)))
}
Predicate::Pattern(pattern) => Predicate::Pattern(pattern.clone()),
Predicate::IsNull(expression) => {
Predicate::IsNull(substitute_expression_value(expression, variable, value))
}
Predicate::IsNotNull(expression) => {
Predicate::IsNotNull(substitute_expression_value(expression, variable, value))
}
Predicate::Exists(operand) => {
Predicate::Exists(substitute_operand_value(operand, variable, value))
}
Predicate::ExistsSubquery(matches) => Predicate::ExistsSubquery(matches.clone()),
Predicate::Boolean(expression) => {
Predicate::Boolean(substitute_expression_value(expression, variable, value))
}
}
}
fn substitute_operand_value(operand: &Operand, variable: &str, value: &Value) -> Operand {
match operand {
Operand::Variable(name) if name == variable => Operand::Literal(value.clone()),
Operand::Literal(_) | Operand::Parameter(_) | Operand::Variable(_) => operand.clone(),
Operand::Property {
variable: item_variable,
key,
} => Operand::Property {
variable: item_variable.clone(),
key: key.clone(),
},
Operand::DynamicProperty {
variable: item_variable,
key,
} => Operand::DynamicProperty {
variable: item_variable.clone(),
key: Box::new(substitute_expression_value(key, variable, value)),
},
}
}
fn remove_item_variable(item: &RemoveItem) -> String {
match item {
RemoveItem::Property { variable, .. } | RemoveItem::Label { variable, .. } => {
variable.clone()
}
}
}
fn matched_relationship_variables(matches: &[MatchClause]) -> BTreeSet<String> {
matches
.iter()
.flat_map(|clause| &clause.patterns)
.flat_map(|pattern| &pattern.chains)
.filter_map(|chain| chain.relationship.variable.clone())
.collect()
}
fn apply_set_item(
storage: &mut dyn WritableStorage,
ids: &BTreeMap<String, EntityId>,
entity_id: EntityId,
item: &SetItem,
params: &Params,
) -> Result<()> {
match item {
SetItem::Property {
key, expression, ..
} => {
let value = evaluate_write_expression_with_entities(storage, ids, expression, params)?;
match (entity_id, value) {
(EntityId::Node(node_id), Value::Null) => {
storage.remove_node_property(node_id, key)?;
}
(EntityId::Node(node_id), value) => {
storage.set_node_property(node_id, key.clone(), value)?;
}
(EntityId::Relationship(relationship_id), Value::Null) => {
storage.remove_relationship_property(relationship_id, key)?;
}
(EntityId::Relationship(relationship_id), value) => {
storage.set_relationship_property(relationship_id, key.clone(), value)?;
}
}
Ok(())
}
SetItem::PropertiesReplace { expression, .. } => {
let properties = evaluate_write_map_expression_with_entities(
storage, ids, expression, params, "SET =", true,
)?;
match entity_id {
EntityId::Node(node_id) => storage.replace_node_properties(node_id, properties),
EntityId::Relationship(relationship_id) => {
storage.replace_relationship_properties(relationship_id, properties)
}
}
}
SetItem::PropertiesMerge { expression, .. } => {
let properties = evaluate_write_map_expression_with_entities(
storage, ids, expression, params, "SET +=", false,
)?;
for (key, value) in properties {
match (entity_id, value) {
(EntityId::Node(node_id), Value::Null) => {
storage.remove_node_property(node_id, &key)?;
}
(EntityId::Node(node_id), value) => {
storage.set_node_property(node_id, key, value)?;
}
(EntityId::Relationship(relationship_id), Value::Null) => {
storage.remove_relationship_property(relationship_id, &key)?;
}
(EntityId::Relationship(relationship_id), value) => {
storage.set_relationship_property(relationship_id, key, value)?;
}
}
}
Ok(())
}
SetItem::Label { labels, .. } => {
let EntityId::Node(node_id) = entity_id else {
return Err(Error::Validation(
"SET label item requires a node binding".to_string(),
));
};
for label in labels {
storage.set_node_label(node_id, label.clone())?;
}
Ok(())
}
}
}
fn evaluate_write_map_expression_with_entities(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
expression: &Expression,
params: &Params,
operator: &str,
drop_null_values: bool,
) -> Result<Properties> {
let value = evaluate_write_expression_with_entities(storage, ids, expression, params)?;
let Value::Map(properties) = value else {
return Err(Error::Validation(format!(
"{operator} requires a map expression"
)));
};
if drop_null_values {
Ok(properties
.into_iter()
.filter(|(_, value)| !matches!(value, Value::Null))
.collect())
} else {
Ok(properties)
}
}
fn apply_remove_item(
storage: &mut dyn WritableStorage,
entity_id: EntityId,
item: &RemoveItem,
) -> Result<()> {
match item {
RemoveItem::Property { key, .. } => match entity_id {
EntityId::Node(node_id) => storage.remove_node_property(node_id, key),
EntityId::Relationship(relationship_id) => {
storage.remove_relationship_property(relationship_id, key)
}
},
RemoveItem::Label { labels, .. } => {
let EntityId::Node(node_id) = entity_id else {
return Err(Error::Validation(
"REMOVE label item requires a node binding".to_string(),
));
};
for label in labels {
storage.remove_node_label(node_id, label)?;
}
Ok(())
}
}
}
fn relationship_write_endpoints(
start: NodeId,
end: NodeId,
direction: Direction,
) -> (NodeId, NodeId) {
match direction {
Direction::Outgoing | Direction::Undirected => (start, end),
Direction::Incoming => (end, start),
}
}
fn relationship_matches_merge_properties(
storage: &dyn StorageInterface,
relationship: &crate::graph_model::Relationship,
relationship_types: &[String],
properties: &Properties,
) -> Result<bool> {
Ok(
controlled_position(storage, relationship_types, |relationship_type| {
relationship_type == &relationship.r#type
})?
.is_some()
&& properties
.iter()
.all(|(key, value)| relationship.properties.get(key) == Some(value)),
)
}
fn apply_merge_actions(
storage: &mut dyn WritableStorage,
entity_id: EntityId,
variable: &str,
created: bool,
actions: &[MergeAction],
params: &Params,
) -> Result<()> {
let selected_branch = if created {
MergeBranch::OnCreate
} else {
MergeBranch::OnMatch
};
for action in actions
.iter()
.filter(|action| action.branch == selected_branch)
{
for item in &action.items {
let item_variable = set_item_variable(item);
if item_variable != variable {
return Err(Error::Validation(format!(
"MERGE action SET target `{}` must match MERGE variable `{variable}`",
item_variable
)));
}
let ids = BTreeMap::from([(variable.to_string(), entity_id)]);
apply_set_item(storage, &ids, entity_id, item, params)?;
}
}
Ok(())
}
struct RelationshipCreatePattern {
start_variable: String,
end_variable: String,
relationship: RelationshipPattern,
}
fn relationship_create_pattern(pattern: &Pattern) -> Result<RelationshipCreatePattern> {
if pattern.variable.is_some() || pattern.shortest_path.is_some() || pattern.chains.len() != 1 {
return Err(Error::UnsupportedQueryFeature(
"CREATE relationship currently supports a single relationship pattern".to_string(),
));
}
let start_variable = pattern.start.variable.clone().ok_or_else(|| {
Error::Validation("CREATE relationship start node must use a variable".to_string())
})?;
let chain = pattern
.chains
.first()
.ok_or_else(|| Error::Parse("CREATE relationship is missing relationship".to_string()))?;
let end_variable = chain.node.variable.clone().ok_or_else(|| {
Error::Validation("CREATE relationship end node must use a variable".to_string())
})?;
if chain.relationship.variable_length {
return Err(Error::UnsupportedQueryFeature(
"CREATE variable-length relationships are not supported".to_string(),
));
}
Ok(RelationshipCreatePattern {
start_variable,
end_variable,
relationship: chain.relationship.clone(),
})
}
fn relationship_create_patterns(pattern: &Pattern) -> Result<Vec<RelationshipCreatePattern>> {
if pattern.shortest_path.is_some() || pattern.chains.is_empty() {
return Err(Error::UnsupportedQueryFeature(
"CREATE relationship currently supports relationship patterns".to_string(),
));
}
pattern
.chains
.iter()
.map(|chain| {
let start_variable = chain.left_variable.clone().ok_or_else(|| {
Error::Validation("CREATE relationship start node must use a variable".to_string())
})?;
let end_variable = chain.node.variable.clone().ok_or_else(|| {
Error::Validation("CREATE relationship end node must use a variable".to_string())
})?;
if chain.relationship.variable_length {
return Err(Error::UnsupportedQueryFeature(
"CREATE variable-length relationships are not supported".to_string(),
));
}
Ok(RelationshipCreatePattern {
start_variable,
end_variable,
relationship: chain.relationship.clone(),
})
})
.collect()
}
fn relationship_create_type(relationship: &RelationshipPattern) -> Result<String> {
match relationship.types.as_slice() {
[] => Err(Error::Validation(
"CREATE relationship requires a relationship type".to_string(),
)),
[r#type, ..] => Ok(r#type.clone()),
}
}
fn relationship_properties_with_entities(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
relationship: &RelationshipPattern,
params: &Params,
) -> Result<Properties> {
relationship
.properties
.iter()
.map(|property| {
evaluate_write_expression_with_entities(storage, ids, &property.expression, params)
.map(|value| (property.key.clone(), value))
})
.collect()
}
fn entity_id_from_external_id(
storage: &dyn StorageInterface,
external_id: &str,
relationship: bool,
) -> Result<EntityId> {
if relationship {
if let Some(relationship_id) = storage.relationship_by_external_id(external_id) {
return Ok(EntityId::Relationship(relationship_id));
}
} else if let Some(node_id) = storage.node_by_external_id(external_id) {
return Ok(EntityId::Node(node_id));
}
Err(Error::Validation(
"SET target variable must bind a node or relationship".to_string(),
))
}
fn relationship_merge_endpoint_variables(
matches: &[MatchClause],
start_variable: &str,
end_variable: &str,
) -> Vec<String> {
let mut variables = Vec::new();
for clause in matches {
for pattern in &clause.patterns {
collect_pattern_entity_variables(pattern, &mut variables);
}
}
push_unique_string(&mut variables, start_variable);
push_unique_string(&mut variables, end_variable);
variables
}
fn relationship_create_endpoint_variables(patterns: &[RelationshipCreatePattern]) -> Vec<String> {
let mut variables = Vec::new();
for pattern in patterns {
push_unique_string(&mut variables, &pattern.start_variable);
push_unique_string(&mut variables, &pattern.end_variable);
}
variables
}
fn relationship_create_variables(patterns: &[RelationshipCreatePattern]) -> Vec<String> {
let mut variables = Vec::new();
for pattern in patterns {
if let Some(variable) = &pattern.relationship.variable {
push_unique_string(&mut variables, variable);
}
}
variables
}
fn collect_pattern_entity_variables(pattern: &Pattern, variables: &mut Vec<String>) {
if let Some(variable) = &pattern.start.variable {
push_unique_string(variables, variable);
}
for chain in &pattern.chains {
if let Some(variable) = &chain.relationship.variable {
push_unique_string(variables, variable);
}
if let Some(variable) = &chain.node.variable {
push_unique_string(variables, variable);
}
}
}
fn push_unique_string(values: &mut Vec<String>, value: &str) {
if !values.iter().any(|existing| existing == value) {
values.push(value.to_string());
}
}
fn element_id_return_items(variables: &[String]) -> Vec<ReturnItem> {
variables
.iter()
.map(|variable| ReturnItem {
expression: ReturnExpression::ElementId(variable.clone()),
alias: Some(variable.clone()),
})
.collect()
}
fn entity_ids_from_row(
storage: &dyn StorageInterface,
columns: &[String],
row: &Record,
relationship_variables: &BTreeSet<String>,
) -> Result<BTreeMap<String, EntityId>> {
let mut ids = BTreeMap::new();
for (index, variable) in columns.iter().enumerate() {
match row.values.get(index) {
Some(Value::String(external_id)) => {
ids.insert(
variable.clone(),
entity_id_from_external_id(
storage,
external_id,
relationship_variables.contains(variable),
)?,
);
}
Some(Value::Null) => {}
_ => {
return Err(Error::Validation(
"relationship endpoints must be matched by node variables".to_string(),
))
}
}
}
Ok(ids)
}
fn node_id_from_entities(
ids: &BTreeMap<String, EntityId>,
variable: &str,
role: &str,
) -> Result<NodeId> {
match ids.get(variable) {
Some(EntityId::Node(node_id)) => Ok(*node_id),
Some(EntityId::Relationship(_)) => Err(Error::Validation(format!(
"CREATE relationship {role} variable `{variable}` must bind a node"
))),
None => Err(Error::Validation(format!(
"CREATE relationship {role} node must be matched by variable"
))),
}
}
fn evaluate_write_expression(expression: &Expression, params: &Params) -> Result<Value> {
match expression {
Expression::Literal(value) => Ok(value.clone()),
Expression::Operand(Operand::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::Parameter(name)) => params
.get(name)
.cloned()
.ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
Expression::Add(left, right) => {
evaluate_write_arithmetic_expression(left, right, WriteArithmeticOperator::Add, params)
}
Expression::Subtract(left, right) => evaluate_write_arithmetic_expression(
left,
right,
WriteArithmeticOperator::Subtract,
params,
),
Expression::Multiply(left, right) => evaluate_write_arithmetic_expression(
left,
right,
WriteArithmeticOperator::Multiply,
params,
),
Expression::Divide(left, right) => evaluate_write_arithmetic_expression(
left,
right,
WriteArithmeticOperator::Divide,
params,
),
Expression::Modulo(left, right) => evaluate_write_arithmetic_expression(
left,
right,
WriteArithmeticOperator::Modulo,
params,
),
Expression::ToLower(expression) => evaluate_write_string_case_value(
evaluate_write_expression(expression, params)?,
WriteStringCaseFunction::Lower,
),
Expression::ToUpper(expression) => evaluate_write_string_case_value(
evaluate_write_expression(expression, params)?,
WriteStringCaseFunction::Upper,
),
Expression::ToString(expression) => {
evaluate_write_to_string_value(evaluate_write_expression(expression, params)?)
}
Expression::ToInteger(expression) => {
evaluate_write_to_integer_value(evaluate_write_expression(expression, params)?)
}
Expression::ToFloat(expression) => {
evaluate_write_to_float_value(evaluate_write_expression(expression, params)?)
}
Expression::ToBoolean(expression) => {
evaluate_write_to_boolean_value(evaluate_write_expression(expression, params)?)
}
Expression::ToStringOrNull(expression) => {
evaluate_write_to_string_or_null_value(evaluate_write_expression(expression, params)?)
}
Expression::ToIntegerOrNull(expression) => {
evaluate_write_to_integer_or_null_value(evaluate_write_expression(expression, params)?)
}
Expression::ToFloatOrNull(expression) => {
evaluate_write_to_float_or_null_value(evaluate_write_expression(expression, params)?)
}
Expression::ToBooleanOrNull(expression) => {
evaluate_write_to_boolean_or_null_value(evaluate_write_expression(expression, params)?)
}
Expression::IsEmpty(expression) => {
evaluate_write_is_empty_value(evaluate_write_expression(expression, params)?)
}
Expression::Head(expression) => {
evaluate_write_head_value(evaluate_write_expression(expression, params)?)
}
Expression::Last(expression) => {
evaluate_write_last_value(evaluate_write_expression(expression, params)?)
}
Expression::Tail(expression) => {
evaluate_write_tail_value(evaluate_write_expression(expression, params)?)
}
Expression::Range { start, end, step } => evaluate_write_range_value(
evaluate_write_expression(start, params)?,
evaluate_write_expression(end, params)?,
step.as_ref()
.map(|step| evaluate_write_expression(step, params))
.transpose()?,
None,
),
Expression::ListIndex { value, index } => evaluate_write_list_index_value(
evaluate_write_expression(value, params)?,
evaluate_write_expression(index, params)?,
),
Expression::ListSlice { value, start, end } => evaluate_write_list_slice_value(
evaluate_write_expression(value, params)?,
start
.as_ref()
.map(|start| evaluate_write_expression(start, params))
.transpose()?,
end.as_ref()
.map(|end| evaluate_write_expression(end, params))
.transpose()?,
),
Expression::Size(expression) => {
evaluate_write_size_value(evaluate_write_expression(expression, params)?)
}
Expression::Substring {
value,
start,
length,
} => evaluate_write_substring_value(
evaluate_write_expression(value, params)?,
evaluate_write_expression(start, params)?,
length
.as_ref()
.map(|length| evaluate_write_expression(length, params))
.transpose()?,
),
Expression::Replace {
value,
search,
replacement,
} => evaluate_write_replace_value(
evaluate_write_expression(value, params)?,
evaluate_write_expression(search, params)?,
evaluate_write_expression(replacement, params)?,
),
Expression::Trim { mode, expression } => {
evaluate_write_trim_value(evaluate_write_expression(expression, params)?, mode)
}
Expression::Split { value, delimiter } => evaluate_write_split_value(
evaluate_write_expression(value, params)?,
evaluate_write_expression(delimiter, params)?,
),
Expression::StringSlice {
mode,
value,
length,
} => evaluate_write_string_slice_value(
evaluate_write_expression(value, params)?,
evaluate_write_expression(length, params)?,
mode,
),
Expression::Reverse(expression) => {
evaluate_write_reverse_value(evaluate_write_expression(expression, params)?)
}
Expression::Abs(expression) => {
evaluate_write_abs_value(evaluate_write_expression(expression, params)?)
}
Expression::Rounding { mode, expression } => {
evaluate_write_rounding_value(evaluate_write_expression(expression, params)?, mode)
}
Expression::Sign(expression) => {
evaluate_write_sign_value(evaluate_write_expression(expression, params)?)
}
Expression::Sqrt(expression) => {
evaluate_write_sqrt_value(evaluate_write_expression(expression, params)?)
}
Expression::Round(expression) => {
evaluate_write_round_value(evaluate_write_expression(expression, params)?)
}
Expression::Log(expression) => {
evaluate_write_log_value(evaluate_write_expression(expression, params)?)
}
Expression::Log10(expression) => {
evaluate_write_log10_value(evaluate_write_expression(expression, params)?)
}
Expression::Exp(expression) => {
evaluate_write_exp_value(evaluate_write_expression(expression, params)?)
}
Expression::AngleConversion { mode, expression } => evaluate_write_angle_conversion_value(
evaluate_write_expression(expression, params)?,
mode,
),
Expression::Trigonometric { mode, expression } => {
evaluate_write_trigonometric_value(evaluate_write_expression(expression, params)?, mode)
}
Expression::InverseTrigonometric { mode, expression } => {
evaluate_write_inverse_trigonometric_value(
evaluate_write_expression(expression, params)?,
mode,
)
}
Expression::Atan2 { y, x } => evaluate_write_atan2_value(
evaluate_write_expression(y, params)?,
evaluate_write_expression(x, params)?,
),
Expression::Haversin(expression) => {
evaluate_write_haversin_value(evaluate_write_expression(expression, params)?)
}
Expression::Pi => Ok(Value::Float(std::f64::consts::PI)),
Expression::E => Ok(Value::Float(std::f64::consts::E)),
Expression::List(items) => items
.iter()
.map(|item| evaluate_write_expression(item, params))
.collect::<Result<Vec<_>>>()
.map(Value::List),
Expression::ListComprehension {
variable,
list,
predicate,
projection,
} => evaluate_contextless_write_list_comprehension(
variable,
evaluate_write_expression(list, params)?,
predicate.as_deref(),
projection,
params,
),
Expression::ListPredicate {
mode,
variable,
list,
predicate,
} => evaluate_contextless_write_list_predicate(
*mode,
variable,
evaluate_write_expression(list, params)?,
predicate,
params,
),
Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => evaluate_contextless_write_reduce(
accumulator,
evaluate_write_expression(initial, params)?,
variable,
evaluate_write_expression(list, params)?,
expression,
params,
),
Expression::Map(entries) => entries
.iter()
.map(|(key, expression)| {
evaluate_write_expression(expression, params).map(|value| (key.clone(), value))
})
.collect::<Result<BTreeMap<_, _>>>()
.map(Value::Map),
Expression::Coalesce(items) => {
for item in items {
let value = evaluate_write_expression(item, params)?;
if value != Value::Null {
return Ok(value);
}
}
Ok(Value::Null)
}
Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
if evaluate_contextless_write_predicate(&alternative.predicate, params)? {
return evaluate_write_expression(&alternative.expression, params);
}
}
evaluate_write_expression(else_expression, params)
}
Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
let operand = evaluate_write_expression(operand, params)?;
for alternative in alternatives {
let value = evaluate_write_expression(&alternative.value, params)?;
if compare_write_values(&operand, ComparisonOperator::Equal, &value) {
return evaluate_write_expression(&alternative.expression, params);
}
}
evaluate_write_expression(else_expression, params)
}
Expression::Predicate(predicate) => {
evaluate_contextless_write_predicate(predicate, params).map(Value::Boolean)
}
_ => Err(Error::UnsupportedQueryFeature(
"write property values currently support literal and parameter values".to_string(),
)),
}
}
fn evaluate_contextless_write_predicate(predicate: &Predicate, params: &Params) -> Result<bool> {
match predicate {
Predicate::Comparison {
left,
operator,
right,
} => {
let left = evaluate_write_expression(left, params)?;
let right = evaluate_write_expression(right, params)?;
Ok(compare_write_values(&left, *operator, &right))
}
Predicate::In { item, list } => {
let item = evaluate_write_expression(item, params)?;
let list = evaluate_write_expression(list, params)?;
evaluate_write_in_predicate(list, item, None)
}
Predicate::StringMatch {
left,
operator,
right,
} => {
let left = evaluate_write_expression(left, params)?;
let right = evaluate_write_expression(right, params)?;
evaluate_write_string_predicate(&left, *operator, &right)
}
Predicate::And(left, right) => Ok(evaluate_contextless_write_predicate(left, params)?
&& evaluate_contextless_write_predicate(right, params)?),
Predicate::Or(left, right) => Ok(evaluate_contextless_write_predicate(left, params)?
|| evaluate_contextless_write_predicate(right, params)?),
Predicate::Xor(left, right) => Ok(evaluate_contextless_write_predicate(left, params)?
^ evaluate_contextless_write_predicate(right, params)?),
Predicate::Not(inner) => Ok(!evaluate_contextless_write_predicate(inner, params)?),
Predicate::Pattern(_) => Err(Error::UnsupportedQueryFeature(
"pattern predicates require a matched row context".to_string(),
)),
Predicate::IsNull(expression) => {
Ok(evaluate_write_expression(expression, params)? == Value::Null)
}
Predicate::IsNotNull(expression) => {
Ok(evaluate_write_expression(expression, params)? != Value::Null)
}
Predicate::Exists(operand) => {
Ok(evaluate_contextless_write_operand(operand, params)? != Value::Null)
}
Predicate::ExistsSubquery(_) => Err(Error::UnsupportedQueryFeature(
"write expressions do not support EXISTS subqueries without a matched row context"
.to_string(),
)),
Predicate::Boolean(expression) => match evaluate_write_expression(expression, params)? {
Value::Boolean(value) => Ok(value),
Value::Null => Ok(false),
_ => Err(Error::Validation(
"bare operands must evaluate to boolean".to_string(),
)),
},
}
}
fn evaluate_contextless_write_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::Property { .. } | Operand::DynamicProperty { .. } | Operand::Variable(_) => Err(
Error::Validation("write property expression variable is not bound".to_string()),
),
}
}
fn evaluate_write_expression_with_entities(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
expression: &Expression,
params: &Params,
) -> Result<Value> {
match expression {
Expression::Operand(Operand::Property { variable, key }) => {
entity_property_value(storage, ids, variable, key)
}
Expression::Operand(Operand::DynamicProperty { variable, key }) => {
let key = evaluate_write_expression_with_entities(storage, ids, key, params)?;
let Value::String(key) = key else {
return Err(Error::Validation(
"dynamic property keys must evaluate to strings".to_string(),
));
};
entity_property_value(storage, ids, variable, &key)
}
Expression::Add(left, right) => evaluate_write_arithmetic_expression_with_entities(
storage,
ids,
left,
right,
WriteArithmeticOperator::Add,
params,
),
Expression::Subtract(left, right) => evaluate_write_arithmetic_expression_with_entities(
storage,
ids,
left,
right,
WriteArithmeticOperator::Subtract,
params,
),
Expression::Multiply(left, right) => evaluate_write_arithmetic_expression_with_entities(
storage,
ids,
left,
right,
WriteArithmeticOperator::Multiply,
params,
),
Expression::Divide(left, right) => evaluate_write_arithmetic_expression_with_entities(
storage,
ids,
left,
right,
WriteArithmeticOperator::Divide,
params,
),
Expression::Modulo(left, right) => evaluate_write_arithmetic_expression_with_entities(
storage,
ids,
left,
right,
WriteArithmeticOperator::Modulo,
params,
),
Expression::ToLower(expression) => evaluate_write_string_case_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
WriteStringCaseFunction::Lower,
),
Expression::ToUpper(expression) => evaluate_write_string_case_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
WriteStringCaseFunction::Upper,
),
Expression::ToString(expression) => evaluate_write_to_string_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::ToInteger(expression) => evaluate_write_to_integer_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::ToFloat(expression) => evaluate_write_to_float_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::ToBoolean(expression) => evaluate_write_to_boolean_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::ToStringOrNull(expression) => evaluate_write_to_string_or_null_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::ToIntegerOrNull(expression) => evaluate_write_to_integer_or_null_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::ToFloatOrNull(expression) => evaluate_write_to_float_or_null_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::ToBooleanOrNull(expression) => evaluate_write_to_boolean_or_null_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::IsEmpty(expression) => evaluate_write_is_empty_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Head(expression) => evaluate_write_head_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Last(expression) => evaluate_write_last_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Tail(expression) => evaluate_write_tail_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Range { start, end, step } => evaluate_write_range_value(
evaluate_write_expression_with_entities(storage, ids, start, params)?,
evaluate_write_expression_with_entities(storage, ids, end, params)?,
step.as_ref()
.map(|step| evaluate_write_expression_with_entities(storage, ids, step, params))
.transpose()?,
Some(storage),
),
Expression::ListIndex { value, index } => evaluate_write_list_index_value(
evaluate_write_expression_with_entities(storage, ids, value, params)?,
evaluate_write_expression_with_entities(storage, ids, index, params)?,
),
Expression::ListSlice { value, start, end } => evaluate_write_list_slice_value(
evaluate_write_expression_with_entities(storage, ids, value, params)?,
start
.as_ref()
.map(|start| evaluate_write_expression_with_entities(storage, ids, start, params))
.transpose()?,
end.as_ref()
.map(|end| evaluate_write_expression_with_entities(storage, ids, end, params))
.transpose()?,
),
Expression::Size(expression) => evaluate_write_size_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Substring {
value,
start,
length,
} => evaluate_write_substring_value(
evaluate_write_expression_with_entities(storage, ids, value, params)?,
evaluate_write_expression_with_entities(storage, ids, start, params)?,
length
.as_ref()
.map(|length| evaluate_write_expression_with_entities(storage, ids, length, params))
.transpose()?,
),
Expression::Replace {
value,
search,
replacement,
} => evaluate_write_replace_value(
evaluate_write_expression_with_entities(storage, ids, value, params)?,
evaluate_write_expression_with_entities(storage, ids, search, params)?,
evaluate_write_expression_with_entities(storage, ids, replacement, params)?,
),
Expression::Trim { mode, expression } => evaluate_write_trim_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
mode,
),
Expression::Split { value, delimiter } => evaluate_write_split_value(
evaluate_write_expression_with_entities(storage, ids, value, params)?,
evaluate_write_expression_with_entities(storage, ids, delimiter, params)?,
),
Expression::StringSlice {
mode,
value,
length,
} => evaluate_write_string_slice_value(
evaluate_write_expression_with_entities(storage, ids, value, params)?,
evaluate_write_expression_with_entities(storage, ids, length, params)?,
mode,
),
Expression::Reverse(expression) => evaluate_write_reverse_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Abs(expression) => evaluate_write_abs_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Rounding { mode, expression } => evaluate_write_rounding_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
mode,
),
Expression::Sign(expression) => evaluate_write_sign_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Sqrt(expression) => evaluate_write_sqrt_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Round(expression) => evaluate_write_round_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Log(expression) => evaluate_write_log_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Log10(expression) => evaluate_write_log10_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Exp(expression) => evaluate_write_exp_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::AngleConversion { mode, expression } => evaluate_write_angle_conversion_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
mode,
),
Expression::Trigonometric { mode, expression } => evaluate_write_trigonometric_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
mode,
),
Expression::InverseTrigonometric { mode, expression } => {
evaluate_write_inverse_trigonometric_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
mode,
)
}
Expression::Atan2 { y, x } => evaluate_write_atan2_value(
evaluate_write_expression_with_entities(storage, ids, y, params)?,
evaluate_write_expression_with_entities(storage, ids, x, params)?,
),
Expression::Haversin(expression) => evaluate_write_haversin_value(
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
),
Expression::Pi => Ok(Value::Float(std::f64::consts::PI)),
Expression::E => Ok(Value::Float(std::f64::consts::E)),
Expression::List(items) => items
.iter()
.map(|item| evaluate_write_expression_with_entities(storage, ids, item, params))
.collect::<Result<Vec<_>>>()
.map(Value::List),
Expression::ListComprehension {
variable,
list,
predicate,
projection,
} => evaluate_write_list_comprehension_with_entities(
storage,
ids,
variable,
evaluate_write_expression_with_entities(storage, ids, list, params)?,
predicate.as_deref(),
projection,
params,
),
Expression::ListPredicate {
mode,
variable,
list,
predicate,
} => evaluate_write_list_predicate_with_entities(
storage,
ids,
*mode,
variable,
evaluate_write_expression_with_entities(storage, ids, list, params)?,
predicate,
params,
),
Expression::Reduce {
accumulator,
initial,
variable,
list,
expression,
} => evaluate_write_reduce_with_entities(
storage,
ids,
accumulator,
evaluate_write_expression_with_entities(storage, ids, initial, params)?,
variable,
evaluate_write_expression_with_entities(storage, ids, list, params)?,
expression,
params,
),
Expression::Map(entries) => entries
.iter()
.map(|(key, expression)| {
evaluate_write_expression_with_entities(storage, ids, expression, params)
.map(|value| (key.clone(), value))
})
.collect::<Result<BTreeMap<_, _>>>()
.map(Value::Map),
Expression::MapProjection { variable, items } => {
evaluate_write_map_projection(storage, ids, variable, items, params)
}
Expression::PatternComprehension {
pattern,
predicate,
projection,
} => evaluate_write_pattern_comprehension(
storage,
ids,
pattern,
predicate.as_deref(),
projection,
params,
),
Expression::Coalesce(items) => {
for item in items {
let value = evaluate_write_expression_with_entities(storage, ids, item, params)?;
if value != Value::Null {
return Ok(value);
}
}
Ok(Value::Null)
}
Expression::Case {
alternatives,
else_expression,
} => {
for alternative in alternatives {
if evaluate_write_predicate(storage, ids, &alternative.predicate, params)? {
return evaluate_write_expression_with_entities(
storage,
ids,
&alternative.expression,
params,
);
}
}
evaluate_write_expression_with_entities(storage, ids, else_expression, params)
}
Expression::SimpleCase {
operand,
alternatives,
else_expression,
} => {
let operand = evaluate_write_expression_with_entities(storage, ids, operand, params)?;
for alternative in alternatives {
let value = evaluate_write_expression_with_entities(
storage,
ids,
&alternative.value,
params,
)?;
if compare_write_values(&operand, ComparisonOperator::Equal, &value) {
return evaluate_write_expression_with_entities(
storage,
ids,
&alternative.expression,
params,
);
}
}
evaluate_write_expression_with_entities(storage, ids, else_expression, params)
}
Expression::Predicate(predicate) => {
evaluate_write_predicate(storage, ids, predicate, params).map(Value::Boolean)
}
_ => evaluate_write_expression(expression, params),
}
}
fn evaluate_contextless_write_list_comprehension(
variable: &str,
list: Value,
predicate: Option<&Predicate>,
projection: &Expression,
params: &Params,
) -> Result<Value> {
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 let Some(predicate) = predicate {
let predicate = substitute_predicate_value(predicate, variable, &value);
if !evaluate_contextless_write_predicate(&predicate, params)? {
continue;
}
}
let projection = substitute_expression_value(projection, variable, &value);
output.push(evaluate_write_expression(&projection, params)?);
}
Ok(Value::List(output))
}
fn evaluate_contextless_write_list_predicate(
mode: crate::cypher::ast::ListPredicateMode,
variable: &str,
list: Value,
predicate: &Predicate,
params: &Params,
) -> Result<Value> {
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 {
let predicate = substitute_predicate_value(predicate, variable, value);
if evaluate_contextless_write_predicate(&predicate, params)? {
matches += 1;
}
}
Ok(Value::Boolean(write_list_predicate_result(
mode,
matches,
values.len(),
)))
}
fn evaluate_contextless_write_reduce(
accumulator: &str,
initial: Value,
variable: &str,
list: Value,
expression: &Expression,
params: &Params,
) -> Result<Value> {
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 {
let expression = substitute_expression_value(expression, accumulator, &accumulator_value);
let expression = substitute_expression_value(&expression, variable, &value);
accumulator_value = evaluate_write_expression(&expression, params)?;
}
Ok(accumulator_value)
}
fn evaluate_write_map_projection(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
variable: &str,
items: &[crate::cypher::ast::MapProjectionItem],
params: &Params,
) -> Result<Value> {
let mut values = BTreeMap::new();
for item in items {
match item {
crate::cypher::ast::MapProjectionItem::AllProperties => {
values.extend(entity_properties(storage, ids, variable)?);
}
crate::cypher::ast::MapProjectionItem::Property(key) => {
values.insert(
key.clone(),
entity_property_value(storage, ids, variable, key)?,
);
}
crate::cypher::ast::MapProjectionItem::Variable(variable) => {
values.insert(
variable.clone(),
evaluate_write_operand(
storage,
ids,
&Operand::Variable(variable.clone()),
params,
)?,
);
}
crate::cypher::ast::MapProjectionItem::Expression { key, expression } => {
values.insert(
key.clone(),
evaluate_write_expression_with_entities(storage, ids, expression, params)?,
);
}
}
}
Ok(Value::Map(values))
}
fn evaluate_write_list_comprehension_with_entities(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
variable: &str,
list: Value,
predicate: Option<&Predicate>,
projection: &Expression,
params: &Params,
) -> Result<Value> {
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 (index, value) in values.into_iter().enumerate() {
if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
storage.check_query_control()?;
}
if let Some(predicate) = predicate {
let predicate = substitute_predicate_value(predicate, variable, &value);
if !evaluate_write_predicate(storage, ids, &predicate, params)? {
continue;
}
}
let projection = substitute_expression_value(projection, variable, &value);
output.push(evaluate_write_expression_with_entities(
storage,
ids,
&projection,
params,
)?);
}
Ok(Value::List(output))
}
fn evaluate_write_pattern_comprehension(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
pattern: &Pattern,
predicate: Option<&Predicate>,
projection: &Expression,
params: &Params,
) -> Result<Value> {
if pattern.variable.is_some() || pattern.shortest_path.is_some() || pattern.chains.len() != 1 {
return Err(Error::UnsupportedQueryFeature(
"write pattern comprehension currently supports a single relationship pattern"
.to_string(),
));
}
let chain = &pattern.chains[0];
if chain.relationship.variable_length {
return Err(Error::UnsupportedQueryFeature(
"write pattern comprehension currently supports typed single-hop relationships"
.to_string(),
));
}
let start_id = write_optional_node_binding(ids, pattern.start.variable.as_deref())?;
let end_id = write_optional_node_binding(ids, chain.node.variable.as_deref())?;
let anchor_id = start_id.or(end_id).ok_or_else(|| {
Error::Execution("pattern comprehension is missing a bound endpoint".to_string())
})?;
storage.check_query_control()?;
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<_>>(),
};
let mut values = Vec::new();
for (index, relationship_id) in relationship_ids.into_iter().enumerate() {
if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
storage.check_query_control()?;
}
let relationship = storage.relationship(relationship_id).ok_or_else(|| {
Error::Execution(format!("relationship id {relationship_id} does not exist"))
})?;
if !write_relationship_matches(storage, ids, relationship, &chain.relationship, params)? {
continue;
}
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 mut row_ids = ids.clone();
if let Some(variable) = &pattern.start.variable {
row_ids
.entry(variable.clone())
.or_insert(EntityId::Node(candidate_start));
}
if let Some(variable) = &chain.relationship.variable {
match row_ids.get(variable) {
Some(EntityId::Relationship(bound_id)) if *bound_id == relationship_id => {}
Some(EntityId::Relationship(_)) => continue,
Some(EntityId::Node(_)) => continue,
None => {
row_ids.insert(variable.clone(), EntityId::Relationship(relationship_id));
}
}
}
if let Some(variable) = &chain.node.variable {
row_ids
.entry(variable.clone())
.or_insert(EntityId::Node(candidate_end));
}
let start_node = storage
.node(candidate_start)
.ok_or_else(|| Error::Execution(format!("node id {candidate_start} does not exist")))?;
let end_node = storage
.node(candidate_end)
.ok_or_else(|| Error::Execution(format!("node id {candidate_end} does not exist")))?;
if !write_node_matches(storage, &row_ids, start_node, &pattern.start, params)?
|| !write_node_matches(storage, &row_ids, end_node, &chain.node, params)?
{
continue;
}
if let Some(predicate) = predicate {
if !evaluate_write_predicate(storage, &row_ids, predicate, params)? {
continue;
}
}
values.push(evaluate_write_expression_with_entities(
storage, &row_ids, projection, params,
)?);
}
Ok(Value::List(values))
}
fn evaluate_write_list_predicate_with_entities(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
mode: crate::cypher::ast::ListPredicateMode,
variable: &str,
list: Value,
predicate: &Predicate,
params: &Params,
) -> Result<Value> {
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 (index, value) in values.iter().enumerate() {
if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
storage.check_query_control()?;
}
let predicate = substitute_predicate_value(predicate, variable, value);
if evaluate_write_predicate(storage, ids, &predicate, params)? {
matches += 1;
}
}
Ok(Value::Boolean(write_list_predicate_result(
mode,
matches,
values.len(),
)))
}
#[allow(clippy::too_many_arguments)]
fn evaluate_write_reduce_with_entities(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
accumulator: &str,
initial: Value,
variable: &str,
list: Value,
expression: &Expression,
params: &Params,
) -> Result<Value> {
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 (index, value) in values.into_iter().enumerate() {
if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
storage.check_query_control()?;
}
let expression = substitute_expression_value(expression, accumulator, &accumulator_value);
let expression = substitute_expression_value(&expression, variable, &value);
accumulator_value =
evaluate_write_expression_with_entities(storage, ids, &expression, params)?;
}
Ok(accumulator_value)
}
fn write_list_predicate_result(
mode: crate::cypher::ast::ListPredicateMode,
matches: usize,
len: usize,
) -> bool {
match mode {
crate::cypher::ast::ListPredicateMode::All => matches == len,
crate::cypher::ast::ListPredicateMode::Any => matches > 0,
crate::cypher::ast::ListPredicateMode::None => matches == 0,
crate::cypher::ast::ListPredicateMode::Single => matches == 1,
}
}
fn evaluate_write_predicate(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
predicate: &Predicate,
params: &Params,
) -> Result<bool> {
match predicate {
Predicate::Comparison {
left,
operator,
right,
} => {
let left = evaluate_write_expression_with_entities(storage, ids, left, params)?;
let right = evaluate_write_expression_with_entities(storage, ids, right, params)?;
Ok(compare_write_values(&left, *operator, &right))
}
Predicate::In { item, list } => {
let item = evaluate_write_expression_with_entities(storage, ids, item, params)?;
let list = evaluate_write_expression_with_entities(storage, ids, list, params)?;
evaluate_write_in_predicate(list, item, Some(storage))
}
Predicate::StringMatch {
left,
operator,
right,
} => {
let left = evaluate_write_expression_with_entities(storage, ids, left, params)?;
let right = evaluate_write_expression_with_entities(storage, ids, right, params)?;
evaluate_write_string_predicate(&left, *operator, &right)
}
Predicate::And(left, right) => Ok(evaluate_write_predicate(storage, ids, left, params)?
&& evaluate_write_predicate(storage, ids, right, params)?),
Predicate::Or(left, right) => Ok(evaluate_write_predicate(storage, ids, left, params)?
|| evaluate_write_predicate(storage, ids, right, params)?),
Predicate::Xor(left, right) => Ok(evaluate_write_predicate(storage, ids, left, params)?
^ evaluate_write_predicate(storage, ids, right, params)?),
Predicate::Not(inner) => Ok(!evaluate_write_predicate(storage, ids, inner, params)?),
Predicate::Pattern(pattern) => {
evaluate_write_pattern_predicate(storage, ids, pattern, params)
}
Predicate::IsNull(expression) => Ok(evaluate_write_expression_with_entities(
storage, ids, expression, params,
)? == Value::Null),
Predicate::IsNotNull(expression) => Ok(evaluate_write_expression_with_entities(
storage, ids, expression, params,
)? != Value::Null),
Predicate::Exists(operand) => {
Ok(evaluate_write_operand(storage, ids, operand, params)? != Value::Null)
}
Predicate::ExistsSubquery(matches) => {
evaluate_write_exists_subquery(storage, ids, matches, params)
}
Predicate::Boolean(expression) => {
match evaluate_write_expression_with_entities(storage, ids, expression, params)? {
Value::Boolean(value) => Ok(value),
Value::Null => Ok(false),
_ => Err(Error::Validation(
"bare operands must evaluate to boolean".to_string(),
)),
}
}
}
}
fn evaluate_write_pattern_predicate(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
pattern: &Pattern,
params: &Params,
) -> Result<bool> {
let Some(chain) = pattern.chains.first() else {
return Ok(false);
};
let start_id = write_pattern_node_binding(ids, pattern.start.variable.as_deref())?;
let end_id = write_pattern_node_binding(ids, chain.node.variable.as_deref())?;
let anchor_id = start_id.or(end_id).ok_or_else(|| {
Error::Execution("pattern predicate is missing a bound endpoint".to_string())
})?;
storage.check_query_control()?;
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 (index, relationship_id) in relationship_ids.into_iter().enumerate() {
if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
storage.check_query_control()?;
}
let relationship = storage.relationship(relationship_id).ok_or_else(|| {
Error::Execution(format!("relationship id {relationship_id} does not exist"))
})?;
if !write_relationship_matches(storage, ids, relationship, &chain.relationship, params)? {
continue;
}
if let Some(variable) = &chain.relationship.variable {
match ids.get(variable) {
Some(EntityId::Relationship(bound_id)) if *bound_id == relationship_id => {}
Some(EntityId::Relationship(_)) => continue,
Some(EntityId::Node(_)) => 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(candidate_start)
.ok_or_else(|| Error::Execution(format!("node id {candidate_start} does not exist")))?;
let end_node = storage
.node(candidate_end)
.ok_or_else(|| Error::Execution(format!("node id {candidate_end} does not exist")))?;
if write_node_matches(storage, ids, start_node, &pattern.start, params)?
&& write_node_matches(storage, ids, end_node, &chain.node, params)?
{
return Ok(true);
}
}
Ok(false)
}
fn evaluate_write_exists_subquery(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
matches: &[MatchClause],
params: &Params,
) -> Result<bool> {
for clause in matches {
if clause.optional_match {
return Err(Error::UnsupportedQueryFeature(
"write expressions do not support OPTIONAL MATCH in EXISTS subqueries".to_string(),
));
}
let mut patterns = Vec::with_capacity(1 + clause.patterns.len());
patterns.push(&clause.pattern);
patterns.extend(clause.patterns.iter());
for pattern in patterns {
if !evaluate_write_pattern_predicate(storage, ids, pattern, params)? {
return Ok(false);
}
}
if let Some(predicate) = &clause.predicate {
if !evaluate_write_predicate(storage, ids, predicate, params)? {
return Ok(false);
}
}
}
Ok(!matches.is_empty())
}
fn write_pattern_node_binding(
ids: &BTreeMap<String, EntityId>,
variable: Option<&str>,
) -> Result<Option<NodeId>> {
let Some(variable) = variable else {
return Ok(None);
};
match ids.get(variable) {
Some(EntityId::Node(node_id)) => Ok(Some(*node_id)),
Some(EntityId::Relationship(_)) => Ok(None),
None => Err(Error::Validation(format!(
"variable `{variable}` is not bound"
))),
}
}
fn write_optional_node_binding(
ids: &BTreeMap<String, EntityId>,
variable: Option<&str>,
) -> Result<Option<NodeId>> {
let Some(variable) = variable else {
return Ok(None);
};
match ids.get(variable) {
Some(EntityId::Node(node_id)) => Ok(Some(*node_id)),
Some(EntityId::Relationship(_)) => Ok(None),
None => Ok(None),
}
}
fn write_node_matches(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
node: &crate::graph_model::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);
}
}
write_properties_match(storage, ids, &node.properties, &pattern.properties, params)
}
fn write_relationship_matches(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
relationship: &crate::graph_model::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);
}
write_properties_match(
storage,
ids,
&relationship.properties,
&pattern.properties,
params,
)
}
fn write_properties_match(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
properties: &Properties,
predicates: &[crate::cypher::ast::PropertyPredicate],
params: &Params,
) -> Result<bool> {
for predicate in predicates {
let Some(actual) = properties.get(&predicate.key) else {
return Ok(false);
};
let expected =
evaluate_write_expression_with_entities(storage, ids, &predicate.expression, params)?;
if actual != &expected {
return Ok(false);
}
}
Ok(true)
}
fn evaluate_write_operand(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
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 } => entity_property_value(storage, ids, variable, key),
Operand::DynamicProperty { variable, key } => {
let key = evaluate_write_expression_with_entities(storage, ids, key, params)?;
let Value::String(key) = key else {
return Err(Error::Validation(
"dynamic property keys must evaluate to strings".to_string(),
));
};
entity_property_value(storage, ids, variable, &key)
}
Operand::Variable(variable) => match ids.get(variable) {
Some(EntityId::Node(node_id)) => Ok(Value::String(
storage
.node(*node_id)
.ok_or_else(|| Error::Execution(format!("node id {node_id} does not exist")))?
.external_id
.clone(),
)),
Some(EntityId::Relationship(relationship_id)) => Ok(Value::String(
storage
.relationship(*relationship_id)
.ok_or_else(|| {
Error::Execution(format!(
"relationship id {relationship_id} does not exist"
))
})?
.external_id
.clone(),
)),
None => Err(Error::Validation(format!(
"variable `{variable}` is not bound"
))),
},
}
}
fn entity_property_value(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
variable: &str,
key: &str,
) -> Result<Value> {
match ids.get(variable) {
Some(EntityId::Node(node_id)) => Ok(storage
.node(*node_id)
.ok_or_else(|| Error::Execution(format!("node id {node_id} does not exist")))?
.properties
.get(key)
.cloned()
.unwrap_or(Value::Null)),
Some(EntityId::Relationship(relationship_id)) => Ok(storage
.relationship(*relationship_id)
.ok_or_else(|| {
Error::Execution(format!("relationship id {relationship_id} does not exist"))
})?
.properties
.get(key)
.cloned()
.unwrap_or(Value::Null)),
None => Err(Error::Validation(format!(
"variable `{variable}` is not bound"
))),
}
}
fn entity_properties(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
variable: &str,
) -> Result<Properties> {
match ids.get(variable) {
Some(EntityId::Node(node_id)) => Ok(storage
.node(*node_id)
.ok_or_else(|| Error::Execution(format!("node id {node_id} does not exist")))?
.properties
.clone()),
Some(EntityId::Relationship(relationship_id)) => Ok(storage
.relationship(*relationship_id)
.ok_or_else(|| {
Error::Execution(format!("relationship id {relationship_id} does not exist"))
})?
.properties
.clone()),
None => Err(Error::Validation(format!(
"variable `{variable}` is not bound"
))),
}
}
#[derive(Clone, Copy)]
enum WriteArithmeticOperator {
Add,
Subtract,
Multiply,
Divide,
Modulo,
}
#[derive(Clone, Copy)]
enum WriteStringCaseFunction {
Lower,
Upper,
}
fn evaluate_write_string_case_value(
value: Value,
function: WriteStringCaseFunction,
) -> Result<Value> {
match value {
Value::String(value) => Ok(Value::String(match function {
WriteStringCaseFunction::Lower => value.to_lowercase(),
WriteStringCaseFunction::Upper => value.to_uppercase(),
})),
Value::Null => Ok(Value::Null),
_ => Err(Error::Validation(
"string case functions require string arguments".to_string(),
)),
}
}
fn evaluate_write_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_write_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_write_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_write_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_write_to_string_or_null_value(value: Value) -> Result<Value> {
match evaluate_write_to_string_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_write_to_integer_or_null_value(value: Value) -> Result<Value> {
match evaluate_write_to_integer_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_write_to_float_or_null_value(value: Value) -> Result<Value> {
match evaluate_write_to_float_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_write_to_boolean_or_null_value(value: Value) -> Result<Value> {
match evaluate_write_to_boolean_value(value) {
Ok(value) => Ok(value),
Err(Error::Validation(_)) => Ok(Value::Null),
Err(error) => Err(error),
}
}
fn evaluate_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_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_write_atan2_value(y: Value, x: Value) -> Result<Value> {
if y == Value::Null || x == Value::Null {
return Ok(Value::Null);
}
let y = write_numeric_argument_value(y, "atan2")?;
let x = write_numeric_argument_value(x, "atan2")?;
Ok(Value::Float(y.atan2(x)))
}
fn evaluate_write_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 write_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"
))),
}
}
fn evaluate_write_arithmetic_expression(
left: &Expression,
right: &Expression,
operator: WriteArithmeticOperator,
params: &Params,
) -> Result<Value> {
let left = evaluate_write_expression(left, params)?;
let right = evaluate_write_expression(right, params)?;
evaluate_write_arithmetic_values(&left, &right, operator)
}
fn evaluate_write_arithmetic_expression_with_entities(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
left: &Expression,
right: &Expression,
operator: WriteArithmeticOperator,
params: &Params,
) -> Result<Value> {
let left = evaluate_write_expression_with_entities(storage, ids, left, params)?;
let right = evaluate_write_expression_with_entities(storage, ids, right, params)?;
evaluate_write_arithmetic_values(&left, &right, operator)
}
fn compare_write_values(left: &Value, operator: ComparisonOperator, right: &Value) -> bool {
match operator {
ComparisonOperator::Equal => {
left == right || numeric_write_ordering(left, right) == Some(Ordering::Equal)
}
ComparisonOperator::NotEqual => {
left != right && numeric_write_ordering(left, right) != Some(Ordering::Equal)
}
ComparisonOperator::LessThan => {
numeric_or_scalar_write_ordering(left, right) == Some(Ordering::Less)
}
ComparisonOperator::LessThanOrEqual => matches!(
numeric_or_scalar_write_ordering(left, right),
Some(Ordering::Less | Ordering::Equal)
),
ComparisonOperator::GreaterThan => {
numeric_or_scalar_write_ordering(left, right) == Some(Ordering::Greater)
}
ComparisonOperator::GreaterThanOrEqual => matches!(
numeric_or_scalar_write_ordering(left, right),
Some(Ordering::Greater | Ordering::Equal)
),
}
}
fn evaluate_write_in_predicate(
list: Value,
item: Value,
storage: Option<&dyn StorageInterface>,
) -> Result<bool> {
let Value::List(values) = list else {
return Err(Error::Validation(
"IN right-hand side must be a list".to_string(),
));
};
for chunk in values.chunks(QUERY_CONTROL_COMPARISON_BATCH) {
if let Some(storage) = storage {
storage.check_query_control()?;
}
if chunk.iter().any(|value| {
item == *value || numeric_write_ordering(&item, value) == Some(Ordering::Equal)
}) {
return Ok(true);
}
}
Ok(false)
}
fn evaluate_write_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_write_ordering(left: &Value, right: &Value) -> Option<Ordering> {
numeric_write_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_write_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 evaluate_write_arithmetic_values(
left: &Value,
right: &Value,
operator: WriteArithmeticOperator,
) -> Result<Value> {
match (left, right, operator) {
(Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::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), WriteArithmeticOperator::Add) => {
Ok(Value::String(format!("{left}{right}")))
}
(Value::List(left), Value::List(right), WriteArithmeticOperator::Add) => {
let mut values = left.clone();
values.extend(right.clone());
Ok(Value::List(values))
}
(Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::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), WriteArithmeticOperator::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), WriteArithmeticOperator::Divide) => {
Err(Error::Validation("division by zero".to_string()))
}
(Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::Divide) => {
Ok(Value::Float(*left as f64 / *right as f64))
}
(Value::Integer(_), Value::Integer(0), WriteArithmeticOperator::Modulo) => {
Err(Error::Validation("modulo by zero".to_string()))
}
(Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::Modulo) => {
Ok(Value::Integer(left % right))
}
(Value::Integer(left), Value::Float(right), operator) => {
evaluate_write_float_arithmetic(*left as f64, *right, operator)
}
(Value::Float(left), Value::Integer(right), operator) => {
evaluate_write_float_arithmetic(*left, *right as f64, operator)
}
(Value::Float(left), Value::Float(right), operator) => {
evaluate_write_float_arithmetic(*left, *right, operator)
}
_ => Err(Error::Validation(
"arithmetic operators require numeric operands".to_string(),
)),
}
}
fn evaluate_write_float_arithmetic(
left: f64,
right: f64,
operator: WriteArithmeticOperator,
) -> Result<Value> {
match operator {
WriteArithmeticOperator::Add => Ok(Value::Float(left + right)),
WriteArithmeticOperator::Subtract => Ok(Value::Float(left - right)),
WriteArithmeticOperator::Multiply => Ok(Value::Float(left * right)),
WriteArithmeticOperator::Divide if right == 0.0 => {
Err(Error::Validation("division by zero".to_string()))
}
WriteArithmeticOperator::Divide => Ok(Value::Float(left / right)),
WriteArithmeticOperator::Modulo if right == 0.0 => {
Err(Error::Validation("modulo by zero".to_string()))
}
WriteArithmeticOperator::Modulo => Ok(Value::Float(left % right)),
}
}
fn create_returns(
returns: &ReturnProjection,
created_variable: Option<&str>,
) -> Result<Vec<ReturnItem>> {
match returns {
ReturnProjection::Items(items) => Ok(items.clone()),
ReturnProjection::Star => {
let variable = created_variable.ok_or_else(|| {
Error::Validation("CREATE RETURN * requires a node variable".to_string())
})?;
Ok(vec![ReturnItem {
expression: ReturnExpression::Variable(variable.to_string()),
alias: None,
}])
}
}
}
fn create_relationship_returns(
returns: &ReturnProjection,
path_variable: Option<&str>,
relationship_variables: &[String],
) -> Result<Vec<ReturnItem>> {
match returns {
ReturnProjection::Items(items) => Ok(items.clone()),
ReturnProjection::Star => {
if path_variable.is_none() && relationship_variables.is_empty() {
return Err(Error::Validation(
"CREATE relationship RETURN * requires a relationship variable".to_string(),
));
}
let mut items = Vec::new();
if let Some(variable) = path_variable {
items.push(ReturnItem {
expression: ReturnExpression::Variable(variable.to_string()),
alias: None,
});
}
items.extend(relationship_variables.iter().map(|variable| ReturnItem {
expression: ReturnExpression::Variable(variable.clone()),
alias: None,
}));
Ok(items)
}
}
}
fn project_created_relationships_item(
storage: &dyn StorageInterface,
created: &CreatedRelationshipRow,
item: &ReturnItem,
params: &Params,
) -> Result<Value> {
storage.check_query_control()?;
match &item.expression {
ReturnExpression::Variable(variable)
if created
.path
.as_ref()
.is_some_and(|path| path.variable == *variable) =>
{
created_path_value(
storage,
created.path.as_ref().expect("checked path variable"),
)
}
ReturnExpression::Variable(variable)
| ReturnExpression::Property { variable, .. }
| ReturnExpression::Type(variable)
| ReturnExpression::Properties(variable)
| ReturnExpression::Keys(variable)
| ReturnExpression::ElementId(variable) => {
let relationship_id =
created
.relationships
.get(variable)
.copied()
.ok_or_else(|| {
Error::Validation(
"CREATE relationship RETURN can only reference created relationships"
.to_string(),
)
})?;
project_created_relationship_item(
storage,
relationship_id,
Some(variable),
item,
params,
)
}
ReturnExpression::Length(variable)
if created
.path
.as_ref()
.is_some_and(|path| path.variable == *variable) =>
{
Ok(Value::Integer(
created
.path
.as_ref()
.expect("checked path variable")
.relationships
.len() as i64,
))
}
ReturnExpression::Nodes(variable)
if created
.path
.as_ref()
.is_some_and(|path| path.variable == *variable) =>
{
created_path_nodes_value(
storage,
created.path.as_ref().expect("checked path variable"),
)
}
ReturnExpression::Relationships(variable)
if created
.path
.as_ref()
.is_some_and(|path| path.variable == *variable) =>
{
created_path_relationships_value(
storage,
created.path.as_ref().expect("checked path variable"),
)
}
ReturnExpression::Scalar(expression) => {
evaluate_create_return_expression(storage, expression, params)
}
ReturnExpression::Star => Err(Error::Execution(
"CREATE relationship RETURN * should be expanded before projection".to_string(),
)),
_ => Err(Error::Validation(
"CREATE relationship RETURN can only reference created relationships".to_string(),
)),
}
}
fn created_path_value(storage: &dyn StorageInterface, path: &CreatedPath) -> Result<Value> {
let Value::List(nodes) = created_path_nodes_value(storage, path)? else {
unreachable!("created_path_nodes_value always returns Value::List")
};
let nodes = nodes
.into_iter()
.map(|value| {
let Value::Node(node) = value else {
unreachable!("created_path_nodes_value only returns node values")
};
node
})
.collect::<Vec<_>>();
let Value::List(relationships) = created_path_relationships_value(storage, path)? else {
unreachable!("created_path_relationships_value always returns Value::List")
};
let relationships = relationships
.into_iter()
.map(|value| {
let Value::Relationship(relationship) = value else {
unreachable!("created_path_relationships_value only returns relationship values")
};
relationship
})
.collect::<Vec<_>>();
Ok(Value::Path(crate::PathValue {
nodes,
relationships,
}))
}
fn created_path_nodes_value(storage: &dyn StorageInterface, path: &CreatedPath) -> Result<Value> {
let mut nodes = Vec::with_capacity(path.nodes.len());
for (index, node_id) in path.nodes.iter().enumerate() {
if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
storage.check_query_control()?;
}
let node = storage
.node(*node_id)
.ok_or_else(|| Error::Execution("created path node is missing".to_string()))?;
nodes.push(Value::Node(crate::NodeValue::stored(
*node_id as u64,
node.external_id.clone(),
node.labels.clone(),
node.properties.clone(),
)));
}
Ok(Value::List(nodes))
}
fn created_path_relationships_value(
storage: &dyn StorageInterface,
path: &CreatedPath,
) -> Result<Value> {
let mut relationships = Vec::with_capacity(path.relationships.len());
for (index, relationship_id) in path.relationships.iter().enumerate() {
if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
storage.check_query_control()?;
}
relationships.push(Value::Relationship(relationship_value(
storage,
*relationship_id,
)?));
}
Ok(Value::List(relationships))
}
fn project_created_item(
storage: &dyn StorageInterface,
node_id: NodeId,
created_variable: Option<&str>,
item: &ReturnItem,
params: &Params,
) -> Result<Value> {
storage.check_query_control()?;
match &item.expression {
ReturnExpression::Variable(variable) if Some(variable.as_str()) == created_variable => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
Ok(Value::Node(crate::NodeValue::stored(
node_id as u64,
node.external_id.clone(),
node.labels.clone(),
node.properties.clone(),
)))
}
ReturnExpression::Property { variable, key }
if Some(variable.as_str()) == created_variable =>
{
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
Ok(node.properties.get(key).cloned().unwrap_or(Value::Null))
}
ReturnExpression::Labels(variable) if Some(variable.as_str()) == created_variable => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
Ok(Value::List(
node.labels.iter().cloned().map(Value::String).collect(),
))
}
ReturnExpression::Properties(variable) if Some(variable.as_str()) == created_variable => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
Ok(Value::Map(node.properties.clone()))
}
ReturnExpression::Keys(variable) if Some(variable.as_str()) == created_variable => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
Ok(Value::List(
node.properties.keys().cloned().map(Value::String).collect(),
))
}
ReturnExpression::ElementId(variable) if Some(variable.as_str()) == created_variable => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
Ok(Value::String(node.external_id.clone()))
}
ReturnExpression::Scalar(expression) => {
if let Some(variable) = created_variable {
let ids = BTreeMap::from([(variable.to_string(), EntityId::Node(node_id))]);
evaluate_write_expression_with_entities(storage, &ids, expression, params)
} else {
evaluate_create_return_expression(storage, expression, params)
}
}
ReturnExpression::Star => Err(Error::Execution(
"CREATE RETURN * should be expanded before projection".to_string(),
)),
_ => Err(Error::Validation(
"CREATE RETURN can only reference the created node".to_string(),
)),
}
}
fn project_created_relationship_item(
storage: &dyn StorageInterface,
relationship_id: RelationshipId,
created_variable: Option<&str>,
item: &ReturnItem,
params: &Params,
) -> Result<Value> {
storage.check_query_control()?;
let relationship = storage
.relationship(relationship_id)
.ok_or_else(|| Error::Execution("created relationship is missing".to_string()))?;
match &item.expression {
ReturnExpression::Variable(variable) if Some(variable.as_str()) == created_variable => {
let start = storage.node(relationship.start).ok_or_else(|| {
Error::Execution("relationship start node is missing".to_string())
})?;
let end = storage
.node(relationship.end)
.ok_or_else(|| Error::Execution("relationship end node is missing".to_string()))?;
Ok(Value::Relationship(crate::RelationshipValue::stored(
relationship_id as u64,
relationship.start as u64,
relationship.end as u64,
relationship.external_id.clone(),
start.external_id.clone(),
end.external_id.clone(),
relationship.r#type.clone(),
relationship.properties.clone(),
)))
}
ReturnExpression::Property { variable, key }
if Some(variable.as_str()) == created_variable =>
{
Ok(relationship
.properties
.get(key)
.cloned()
.unwrap_or(Value::Null))
}
ReturnExpression::Type(variable) if Some(variable.as_str()) == created_variable => {
Ok(Value::String(relationship.r#type.clone()))
}
ReturnExpression::Properties(variable) if Some(variable.as_str()) == created_variable => {
Ok(Value::Map(relationship.properties.clone()))
}
ReturnExpression::Keys(variable) if Some(variable.as_str()) == created_variable => {
Ok(Value::List(
relationship
.properties
.keys()
.cloned()
.map(Value::String)
.collect(),
))
}
ReturnExpression::ElementId(variable) if Some(variable.as_str()) == created_variable => {
Ok(Value::String(relationship.external_id.clone()))
}
ReturnExpression::Scalar(expression) => {
evaluate_create_return_expression(storage, expression, params)
}
ReturnExpression::Star => Err(Error::Execution(
"CREATE relationship RETURN * should be expanded before projection".to_string(),
)),
_ => Err(Error::Validation(
"CREATE relationship RETURN can only reference the created relationship".to_string(),
)),
}
}
fn set_returns(
returns: &ReturnProjection,
target_variables: &BTreeSet<String>,
) -> Result<Vec<ReturnItem>> {
match returns {
ReturnProjection::Items(items) => Ok(items.clone()),
ReturnProjection::Star => Ok(target_variables
.iter()
.map(|variable| ReturnItem {
expression: ReturnExpression::Variable(variable.clone()),
alias: None,
})
.collect()),
}
}
fn project_set_item(
storage: &dyn StorageInterface,
ids: &BTreeMap<String, EntityId>,
item: &ReturnItem,
params: &Params,
) -> Result<Value> {
storage.check_query_control()?;
match &item.expression {
ReturnExpression::Variable(variable) => match set_entity_id(ids, variable)? {
EntityId::Node(node_id) => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
Ok(Value::Node(crate::NodeValue::stored(
node_id as u64,
node.external_id.clone(),
node.labels.clone(),
node.properties.clone(),
)))
}
EntityId::Relationship(relationship_id) => {
relationship_value(storage, relationship_id).map(Value::Relationship)
}
},
ReturnExpression::Property { variable, key } => match set_entity_id(ids, variable)? {
EntityId::Node(node_id) => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
Ok(node.properties.get(key).cloned().unwrap_or(Value::Null))
}
EntityId::Relationship(relationship_id) => {
let relationship = storage.relationship(relationship_id).ok_or_else(|| {
Error::Execution("updated relationship is missing".to_string())
})?;
Ok(relationship
.properties
.get(key)
.cloned()
.unwrap_or(Value::Null))
}
},
ReturnExpression::Labels(variable) => {
let EntityId::Node(node_id) = set_entity_id(ids, variable)? else {
return Err(Error::Validation(
"labels() requires a node binding".to_string(),
));
};
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
Ok(Value::List(
node.labels.iter().cloned().map(Value::String).collect(),
))
}
ReturnExpression::Keys(variable) => {
let properties = match set_entity_id(ids, variable)? {
EntityId::Node(node_id) => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
&node.properties
}
EntityId::Relationship(relationship_id) => {
let relationship = storage.relationship(relationship_id).ok_or_else(|| {
Error::Execution("updated relationship is missing".to_string())
})?;
&relationship.properties
}
};
Ok(Value::List(
properties.keys().cloned().map(Value::String).collect(),
))
}
ReturnExpression::Properties(variable) => {
let properties = match set_entity_id(ids, variable)? {
EntityId::Node(node_id) => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
node.properties.clone()
}
EntityId::Relationship(relationship_id) => {
let relationship = storage.relationship(relationship_id).ok_or_else(|| {
Error::Execution("updated relationship is missing".to_string())
})?;
relationship.properties.clone()
}
};
Ok(Value::Map(properties))
}
ReturnExpression::ElementId(variable) => {
let external_id = match set_entity_id(ids, variable)? {
EntityId::Node(node_id) => {
let node = storage
.node(node_id)
.ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
node.external_id.clone()
}
EntityId::Relationship(relationship_id) => {
let relationship = storage.relationship(relationship_id).ok_or_else(|| {
Error::Execution("updated relationship is missing".to_string())
})?;
relationship.external_id.clone()
}
};
Ok(Value::String(external_id))
}
ReturnExpression::Type(variable) => {
let EntityId::Relationship(relationship_id) = set_entity_id(ids, variable)? else {
return Err(Error::Validation(
"type() requires a relationship binding".to_string(),
));
};
let relationship = storage
.relationship(relationship_id)
.ok_or_else(|| Error::Execution("updated relationship is missing".to_string()))?;
Ok(Value::String(relationship.r#type.clone()))
}
ReturnExpression::Scalar(expression) => {
evaluate_write_expression_with_entities(storage, ids, expression, params)
}
ReturnExpression::Star => Err(Error::Execution(
"SET RETURN * should be expanded before projection".to_string(),
)),
_ => Err(Error::Validation(
"SET RETURN currently supports updated node variables and properties".to_string(),
)),
}
}
fn set_entity_id(ids: &BTreeMap<String, EntityId>, variable: &str) -> Result<EntityId> {
ids.get(variable)
.copied()
.ok_or_else(|| Error::Validation(format!("SET RETURN variable `{variable}` is not bound")))
}
fn relationship_value(
storage: &dyn StorageInterface,
relationship_id: RelationshipId,
) -> Result<crate::RelationshipValue> {
let relationship = storage
.relationship(relationship_id)
.ok_or_else(|| Error::Execution("relationship is missing".to_string()))?;
let start = storage
.node(relationship.start)
.ok_or_else(|| Error::Execution("relationship start node is missing".to_string()))?;
let end = storage
.node(relationship.end)
.ok_or_else(|| Error::Execution("relationship end node is missing".to_string()))?;
Ok(crate::RelationshipValue::stored(
relationship_id as u64,
relationship.start as u64,
relationship.end as u64,
relationship.external_id.clone(),
start.external_id.clone(),
end.external_id.clone(),
relationship.r#type.clone(),
relationship.properties.clone(),
))
}
fn evaluate_create_return_expression(
storage: &dyn StorageInterface,
expression: &Expression,
params: &Params,
) -> Result<Value> {
evaluate_write_expression_with_entities(storage, &BTreeMap::new(), expression, params)
}
fn create_return_column(item: &ReturnItem) -> String {
item.alias
.clone()
.unwrap_or_else(|| match &item.expression {
ReturnExpression::Variable(variable) => variable.clone(),
ReturnExpression::Property { variable, key } => format!("{variable}.{key}"),
ReturnExpression::Scalar(Expression::Literal(value))
| ReturnExpression::Scalar(Expression::Operand(Operand::Literal(value))) => {
format!("{value:?}")
}
_ => "expr".to_string(),
})
}
fn deduplicate_rows(storage: &dyn StorageInterface, rows: &mut Vec<Record>) -> Result<()> {
let mut seen = Vec::<Record>::new();
let mut distinct = 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.push(row);
}
}
*rows = distinct;
Ok(())
}
fn query_from_matches(matches: Vec<MatchClause>, returns: ReturnProjection) -> Result<Query> {
let first_match = matches
.first()
.cloned()
.ok_or_else(|| Error::Parse("write statement is missing MATCH".to_string()))?;
Ok(Query {
has_initial_match: true,
optional_match: first_match.optional_match,
pattern: first_match.pattern.clone(),
patterns: first_match.patterns,
predicate: first_match.predicate,
extra_matches: matches.into_iter().skip(1).collect(),
unwinds: Vec::new(),
post_unwind_matches: Vec::new(),
procedure_calls: Vec::new(),
post_procedure_unwinds: Vec::new(),
post_procedure_matches: Vec::new(),
with: None,
with_predicate: None,
with_order_by: Vec::new(),
with_skip: None,
with_limit: None,
post_with_unwinds: Vec::new(),
post_with_matches: Vec::new(),
post_with_procedure_calls: Vec::new(),
post_with_procedure_unwinds: Vec::new(),
post_with_procedure_matches: Vec::new(),
post_with_with: None,
post_with_with_predicate: None,
post_with_with_order_by: Vec::new(),
post_with_with_skip: None,
post_with_with_limit: None,
post_with_with_unwinds: Vec::new(),
post_with_with_matches: Vec::new(),
post_with_with_procedure_calls: Vec::new(),
post_with_with_procedure_unwinds: Vec::new(),
post_with_with_procedure_matches: Vec::new(),
post_with_with_calls: Vec::new(),
calls: Vec::new(),
post_call_unwinds: Vec::new(),
post_call_matches: Vec::new(),
post_call_with: None,
post_call_with_predicate: None,
post_call_with_order_by: Vec::new(),
post_call_with_skip: None,
post_call_with_limit: None,
post_call_with_unwinds: Vec::new(),
post_call_with_matches: Vec::new(),
distinct: false,
returns,
implicit_return: false,
order_by: Vec::new(),
skip: None,
limit: None,
})
}