Skip to main content

littlegraph_core/
api.rs

1use std::cell::Cell;
2use std::cmp::Ordering;
3use std::collections::{BTreeMap, BTreeSet};
4use std::marker::PhantomData;
5use std::path::Path;
6use std::rc::Rc;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtomicOrdering};
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10
11use regex::Regex;
12
13use crate::cypher::ast::{
14    AngleConversionMode, ComparisonOperator, CreateRelationshipStatement, CreateStatement,
15    DeleteStatement, Direction, Expression, ForeachStatement, InverseTrigonometricMode,
16    MatchClause, MergeAction, MergeBranch, MergeStatement, NodePattern, Operand, Pattern,
17    Predicate, Query, RelationshipPattern, RemoveItem, RemoveStatement, ReturnExpression,
18    ReturnItem, ReturnProjection, RoundingMode, SetItem, SetStatement, Statement, StringOperator,
19    StringSliceMode, TrigonometricMode, TrimMode,
20};
21use crate::cypher::executor::{evaluate_write_procedure_invocations, execute, WriteProcedureStage};
22use crate::cypher::parser::parse_statement;
23use crate::cypher::planner::plan;
24use crate::cypher::procedure::{resolve as resolve_procedure, ProcedureHandler, ProcedureMode};
25use crate::error::{Error, Result, TransactionErrorKind};
26use crate::graph_model::{NodeId, RelationshipId};
27use crate::neo4j_backend::{Neo4jBackend, Neo4jBackendSavepoint, WorkspaceUsage};
28use crate::neo4j_storage::{Neo4jStorage, Neo4jWritableStorage};
29use crate::storage_interface::{StorageInterface, WritableStorage};
30use crate::value::{Properties, Value};
31
32pub type Params = BTreeMap<String, Value>;
33
34const QUERY_CONTROL_COMPARISON_BATCH: usize = 256;
35
36fn controlled_position<T>(
37    storage: &dyn StorageInterface,
38    values: &[T],
39    mut predicate: impl FnMut(&T) -> bool,
40) -> Result<Option<usize>> {
41    for (chunk_index, chunk) in values.chunks(QUERY_CONTROL_COMPARISON_BATCH).enumerate() {
42        storage.check_query_control()?;
43        if let Some(offset) = chunk.iter().position(&mut predicate) {
44            return Ok(Some(chunk_index * QUERY_CONTROL_COMPARISON_BATCH + offset));
45        }
46    }
47    Ok(None)
48}
49
50#[derive(Clone, Debug, PartialEq)]
51pub struct Record {
52    pub values: Vec<Value>,
53}
54
55#[derive(Clone, Debug, PartialEq)]
56pub struct QueryResult {
57    pub columns: Vec<String>,
58    pub rows: Vec<Record>,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62enum EntityId {
63    Node(NodeId),
64    Relationship(RelationshipId),
65}
66
67#[derive(Clone, Debug, Default)]
68struct CreatedRelationshipRow {
69    relationships: BTreeMap<String, RelationshipId>,
70    path: Option<CreatedPath>,
71}
72
73#[derive(Clone, Debug)]
74struct CreatedPath {
75    variable: String,
76    nodes: Vec<NodeId>,
77    relationships: Vec<RelationshipId>,
78}
79
80#[derive(Debug)]
81pub struct Graph {
82    backend: Neo4jBackend,
83    query_control: Option<QueryControl>,
84}
85
86#[derive(Clone, Debug)]
87struct QueryControl {
88    deadline: Option<Instant>,
89    cancellation_token: Option<CancellationToken>,
90    max_query_memory_bytes: Option<usize>,
91    query_memory_bytes: Cell<usize>,
92}
93
94impl QueryControl {
95    fn check(&self) -> Result<()> {
96        if self
97            .cancellation_token
98            .as_ref()
99            .is_some_and(CancellationToken::is_cancelled)
100        {
101            Err(Error::Transaction(TransactionErrorKind::Cancelled))
102        } else if self
103            .deadline
104            .is_some_and(|deadline| Instant::now() >= deadline)
105        {
106            Err(Error::Transaction(TransactionErrorKind::TimedOut))
107        } else {
108            Ok(())
109        }
110    }
111
112    fn charge_memory(&self, bytes: usize) -> Result<()> {
113        let total = self
114            .query_memory_bytes
115            .get()
116            .checked_add(bytes)
117            .ok_or(Error::Transaction(TransactionErrorKind::ResourceLimit))?;
118        if self
119            .max_query_memory_bytes
120            .is_some_and(|limit| total > limit)
121        {
122            return Err(Error::Transaction(TransactionErrorKind::ResourceLimit));
123        }
124        self.query_memory_bytes.set(total);
125        Ok(())
126    }
127}
128
129struct ControlledStorage<'a> {
130    storage: &'a dyn StorageInterface,
131    control: Option<&'a QueryControl>,
132}
133
134impl StorageInterface for ControlledStorage<'_> {
135    fn check_query_control(&self) -> Result<()> {
136        self.control.map_or(Ok(()), QueryControl::check)
137    }
138
139    fn charge_query_memory(&self, bytes: usize) -> Result<()> {
140        self.control
141            .map_or(Ok(()), |control| control.charge_memory(bytes))
142    }
143
144    fn database_metadata(&self) -> Option<&crate::storage_interface::DatabaseMetadata> {
145        self.storage.database_metadata()
146    }
147
148    fn schema_metadata(&self) -> Option<&crate::storage_interface::SchemaMetadata> {
149        self.storage.schema_metadata()
150    }
151
152    fn node_ids(&self) -> Vec<NodeId> {
153        self.storage.node_ids()
154    }
155
156    fn relationship_ids(&self) -> Vec<RelationshipId> {
157        self.storage.relationship_ids()
158    }
159
160    fn node(&self, id: NodeId) -> Option<&crate::graph_model::Node> {
161        self.storage.node(id)
162    }
163
164    fn relationship(&self, id: RelationshipId) -> Option<&crate::graph_model::Relationship> {
165        self.storage.relationship(id)
166    }
167
168    fn outgoing_relationships(&self, id: NodeId) -> &[RelationshipId] {
169        self.storage.outgoing_relationships(id)
170    }
171
172    fn incoming_relationships(&self, id: NodeId) -> &[RelationshipId] {
173        self.storage.incoming_relationships(id)
174    }
175
176    fn nodes_with_label(&self, label: &str) -> &[NodeId] {
177        self.storage.nodes_with_label(label)
178    }
179
180    fn node_by_external_id(&self, external_id: &str) -> Option<NodeId> {
181        self.storage.node_by_external_id(external_id)
182    }
183
184    fn relationship_by_external_id(&self, external_id: &str) -> Option<RelationshipId> {
185        self.storage.relationship_by_external_id(external_id)
186    }
187
188    fn label_tokens(&self) -> Vec<String> {
189        self.storage.label_tokens()
190    }
191
192    fn relationship_type_tokens(&self) -> Vec<String> {
193        self.storage.relationship_type_tokens()
194    }
195
196    fn property_key_tokens(&self) -> Vec<String> {
197        self.storage.property_key_tokens()
198    }
199
200    fn node_property_type(&self, id: NodeId, property_key: &str) -> Option<String> {
201        self.storage.node_property_type(id, property_key)
202    }
203
204    fn relationship_property_type(&self, id: RelationshipId, property_key: &str) -> Option<String> {
205        self.storage.relationship_property_type(id, property_key)
206    }
207}
208
209/// Limits and cancellation controls applied to an explicit transaction.
210#[derive(Clone, Debug, Default)]
211pub struct TransactionOptions {
212    /// Maximum duration measured from the start of the transaction.
213    pub timeout: Option<Duration>,
214    /// Absolute deadline. When both deadline and timeout are set, the earlier
215    /// instant wins.
216    pub deadline: Option<Instant>,
217    /// Maximum estimated bytes retained by the writable base snapshot, staged
218    /// record images, and savepoints.
219    pub max_workspace_bytes: Option<usize>,
220    /// Maximum number of staged records retained by the transaction and its
221    /// savepoints.
222    pub max_records: Option<usize>,
223    /// Maximum estimated heap bytes materialized by a single query. This is
224    /// independent from the writable transaction workspace limit.
225    pub max_query_memory_bytes: Option<usize>,
226    /// Spill staged record images to a private temporary file when their
227    /// estimated in-memory payload exceeds this threshold.
228    pub spill_threshold_bytes: Option<usize>,
229    /// Maximum size of the append-only temporary spill file.
230    pub max_spill_bytes: Option<u64>,
231    /// Maximum encoded commit-journal size, including the durable marker.
232    /// This can only tighten the internal 1 GiB recovery limit.
233    pub max_journal_bytes: Option<u64>,
234    /// Optional token that may be cancelled from another thread.
235    pub cancellation_token: Option<CancellationToken>,
236    /// Reject statements and procedures which may write data.
237    pub read_only: bool,
238}
239
240/// A thread-safe signal used to cancel a transaction cooperatively.
241#[derive(Clone, Debug, Default)]
242pub struct CancellationToken {
243    cancelled: Arc<AtomicBool>,
244}
245
246impl CancellationToken {
247    pub fn new() -> Self {
248        Self::default()
249    }
250
251    pub fn cancel(&self) {
252        self.cancelled.store(true, AtomicOrdering::Release);
253    }
254
255    pub fn is_cancelled(&self) -> bool {
256        self.cancelled.load(AtomicOrdering::Acquire)
257    }
258}
259
260/// A graph transaction that is confined to the thread where it was created.
261///
262/// ```compile_fail
263/// use littlegraph_core::Transaction;
264///
265/// fn require_send<T: Send>() {}
266/// require_send::<Transaction<'static>>();
267/// ```
268///
269/// A live transaction exclusively borrows its graph, so query execution cannot
270/// bypass the transaction handle:
271///
272/// ```compile_fail
273/// use littlegraph_core::{Graph, Params};
274///
275/// fn bypass_transaction(graph: &mut Graph) {
276///     let transaction = graph.transaction().unwrap();
277///     graph.query("MATCH (n) RETURN n", Params::new()).unwrap();
278///     drop(transaction);
279/// }
280/// ```
281#[derive(Debug)]
282#[must_use = "dropping a transaction without committing rolls it back"]
283pub struct Transaction<'graph> {
284    graph: &'graph mut Graph,
285    state: TransactionHandleState,
286    id: u64,
287    next_savepoint_id: u64,
288    savepoints: Vec<TransactionSavepoint>,
289    deadline: Option<Instant>,
290    cancellation_token: Option<CancellationToken>,
291    locally_cancelled: bool,
292    max_workspace_bytes: Option<usize>,
293    max_records: Option<usize>,
294    max_query_memory_bytes: Option<usize>,
295    read_only: bool,
296    not_send: PhantomData<Rc<()>>,
297}
298
299/// An opaque checkpoint created by [`Transaction::savepoint`].
300///
301/// Savepoints are bound to the transaction that created them. A token becomes
302/// invalid after it is released or discarded by rolling back to an earlier
303/// savepoint.
304#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
305#[must_use = "retain the token to roll back to or release this savepoint"]
306pub struct Savepoint {
307    transaction_id: u64,
308    id: u64,
309}
310
311#[derive(Debug)]
312struct TransactionSavepoint {
313    token: Savepoint,
314    backend: Neo4jBackendSavepoint,
315    usage: WorkspaceUsage,
316}
317
318static NEXT_TRANSACTION_ID: AtomicU64 = AtomicU64::new(1);
319
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
321enum TransactionHandleState {
322    Active,
323    Failed(TransactionErrorKind),
324    Completed,
325}
326
327impl Graph {
328    /// Open a normally closed Neo4j record-store database as a read-only graph.
329    pub fn open_neo4j(database_directory: impl AsRef<Path>) -> Result<Self> {
330        Ok(Self {
331            backend: Neo4jBackend::ReadOnly(Box::new(Neo4jStorage::open(database_directory)?)),
332            query_control: None,
333        })
334    }
335
336    /// Open a Neo4j record-store database for offline writes.
337    ///
338    /// Writable graphs in this process share an MVCC coordinator and Neo4j's
339    /// database lock. Transactions read a stable snapshot; concurrent writers
340    /// validate physical record images before rebasing disjoint record patches,
341    /// including in-place dynamic chains, and merge counts deltas against the
342    /// latest counts root. ID, token, degree, and dynamic-chain lifecycle
343    /// changes use conservative first-committer-wins conflict detection. Other
344    /// processes and read-only openers remain excluded while a writable graph
345    /// is alive.
346    pub fn open_neo4j_writable(database_directory: impl AsRef<Path>) -> Result<Self> {
347        Ok(Self {
348            backend: Neo4jBackend::Writable(Box::new(Neo4jWritableStorage::open(
349                database_directory,
350            )?)),
351            query_control: None,
352        })
353    }
354
355    pub fn query(&mut self, query: &str, params: Params) -> Result<QueryResult> {
356        let statement = parse_statement(query)?;
357        let is_write = is_write_statement(&statement)?;
358        if !is_write {
359            self.backend.refresh_read_view()?;
360            return self.execute_statement(statement, &params);
361        }
362
363        self.backend
364            .begin_transaction(None, None, None, None, None, None)?;
365        match self.execute_statement(statement, &params) {
366            Ok(result) => {
367                self.backend.commit_transaction()?;
368                Ok(result)
369            }
370            Err(error) => {
371                self.backend.mark_transaction_failed();
372                self.backend.rollback_transaction()?;
373                Err(error)
374            }
375        }
376    }
377
378    /// Begin a transaction that can execute multiple queries atomically.
379    ///
380    /// Dropping the returned handle without committing rolls the transaction
381    /// back. Once a query fails, the transaction is rollback-only.
382    pub fn transaction(&mut self) -> Result<Transaction<'_>> {
383        self.transaction_with_options(TransactionOptions::default())
384    }
385
386    /// Begin a transaction with deadline, cancellation, and workspace limits.
387    pub fn transaction_with_options(
388        &mut self,
389        options: TransactionOptions,
390    ) -> Result<Transaction<'_>> {
391        let id = NEXT_TRANSACTION_ID
392            .try_update(AtomicOrdering::Relaxed, AtomicOrdering::Relaxed, |id| {
393                id.checked_add(1)
394            })
395            .map_err(|_| Error::Execution("transaction identifier space exhausted".to_owned()))?;
396        let timeout_deadline = options
397            .timeout
398            .map(|timeout| {
399                Instant::now().checked_add(timeout).ok_or_else(|| {
400                    Error::Execution("transaction timeout exceeds the supported range".to_owned())
401                })
402            })
403            .transpose()?;
404        let deadline = match (options.deadline, timeout_deadline) {
405            (Some(deadline), Some(timeout_deadline)) => Some(deadline.min(timeout_deadline)),
406            (deadline, timeout_deadline) => deadline.or(timeout_deadline),
407        };
408        self.backend.begin_transaction(
409            options.max_workspace_bytes,
410            options.max_records,
411            options.spill_threshold_bytes,
412            options.max_spill_bytes,
413            options.max_journal_bytes,
414            Some(id),
415        )?;
416        Ok(Transaction {
417            graph: self,
418            state: TransactionHandleState::Active,
419            id,
420            next_savepoint_id: 1,
421            savepoints: Vec::new(),
422            deadline,
423            cancellation_token: options.cancellation_token,
424            locally_cancelled: false,
425            max_workspace_bytes: options.max_workspace_bytes,
426            max_records: options.max_records,
427            max_query_memory_bytes: options.max_query_memory_bytes,
428            read_only: options.read_only,
429            not_send: PhantomData,
430        })
431    }
432
433    /// Execute a transaction closure, retrying a stale snapshot conflict.
434    ///
435    /// `max_retries` counts retries after the initial attempt. The closure is
436    /// re-run from the beginning on each retry, so it should be deterministic
437    /// and must not perform external side effects. Parse, execution, timeout,
438    /// resource, and storage errors are returned without retrying.
439    pub fn run_transaction<F>(&mut self, max_retries: usize, operation: F) -> Result<()>
440    where
441        F: FnMut(&mut Transaction<'_>) -> Result<()>,
442    {
443        self.run_transaction_with_options(TransactionOptions::default(), max_retries, operation)
444    }
445
446    /// Execute a transaction closure with options, retrying snapshot conflicts.
447    ///
448    /// The options are applied afresh to every attempt. In particular, a
449    /// relative timeout starts again for each retry, while an absolute deadline
450    /// remains fixed.
451    pub fn run_transaction_with_options<F>(
452        &mut self,
453        options: TransactionOptions,
454        max_retries: usize,
455        mut operation: F,
456    ) -> Result<()>
457    where
458        F: FnMut(&mut Transaction<'_>) -> Result<()>,
459    {
460        let mut retries = 0;
461        loop {
462            let mut transaction = self.transaction_with_options(options.clone())?;
463            let result = match operation(&mut transaction) {
464                Ok(()) => transaction.commit(),
465                Err(error) => {
466                    drop(transaction);
467                    Err(error)
468                }
469            };
470            match result {
471                Err(Error::Transaction(TransactionErrorKind::Conflict))
472                    if retries < max_retries =>
473                {
474                    retries += 1;
475                }
476                result => return result,
477            }
478        }
479    }
480
481    fn execute_statement(&mut self, statement: Statement, params: &Params) -> Result<QueryResult> {
482        if !self.backend.is_writable()
483            && !matches!(&statement, Statement::Single(_) | Statement::Union { .. })
484        {
485            return Err(Error::UnsupportedWriteQuery(
486                "Neo4j storage is read-only".to_owned(),
487            ));
488        }
489        match statement {
490            Statement::Single(query) => {
491                let plan = plan(query)?;
492                self.execute_plan(plan, params)
493            }
494            Statement::Create(create) => self.execute_create(create, params),
495            Statement::CreateRelationship(create) => {
496                self.execute_create_relationship(create, params)
497            }
498            Statement::Set(set) => self.execute_set(set, params),
499            Statement::Foreach(foreach) => self.execute_foreach(foreach, params),
500            Statement::Delete(delete) => self.execute_delete(delete, params),
501            Statement::Remove(remove) => self.execute_remove(remove, params),
502            Statement::Merge(merge) => self.execute_merge(merge, params),
503            Statement::Union { first, parts } => {
504                let mut result = self.execute_plan(plan(first)?, params)?;
505                let columns = result.columns.clone();
506
507                for part in parts {
508                    let mut next = self.execute_plan(plan(part.query)?, params)?;
509                    if next.columns != columns {
510                        return Err(Error::Validation(format!(
511                            "UNION query columns must match: expected {:?}, got {:?}",
512                            columns, next.columns
513                        )));
514                    }
515
516                    result.rows.append(&mut next.rows);
517                    if !part.all {
518                        deduplicate_rows(&self.read_storage(), &mut result.rows)?;
519                    }
520                }
521
522                Ok(result)
523            }
524        }
525    }
526
527    fn read_storage(&self) -> ControlledStorage<'_> {
528        ControlledStorage {
529            storage: self.backend.read(),
530            control: self.query_control.as_ref(),
531        }
532    }
533
534    fn execute_plan(
535        &mut self,
536        mut plan: crate::cypher::planner::Plan,
537        params: &Params,
538    ) -> Result<QueryResult> {
539        let procedure_stages = [
540            &plan.procedure_calls,
541            &plan.post_with_procedure_calls,
542            &plan.post_with_with_procedure_calls,
543        ];
544        let has_write = procedure_stages
545            .iter()
546            .flat_map(|calls| calls.iter())
547            .any(|call| call.mode == ProcedureMode::Write);
548        if has_write {
549            if procedure_stages
550                .iter()
551                .flat_map(|calls| calls.iter())
552                .any(|call| call.mode != ProcedureMode::Write)
553            {
554                return Err(Error::Validation(
555                    "mixing READ and WRITE procedures in one query is not supported".to_owned(),
556                ));
557            }
558            if procedure_stages
559                .iter()
560                .filter(|calls| !calls.is_empty())
561                .count()
562                != 1
563            {
564                return Err(Error::Validation(
565                    "WRITE procedures in multiple query stages are not supported".to_owned(),
566                ));
567            }
568            let invocations =
569                evaluate_write_procedure_invocations(&self.read_storage(), params, &plan)?;
570            let calls = match invocations.stage {
571                WriteProcedureStage::Initial => &plan.procedure_calls,
572                WriteProcedureStage::PostWith => &plan.post_with_procedure_calls,
573                WriteProcedureStage::PostSecondWith => &plan.post_with_with_procedure_calls,
574            };
575            for (call, arguments_by_row) in calls.iter().zip(invocations.arguments_by_call) {
576                let signature = resolve_procedure(&call.name)?;
577                let ProcedureHandler::Write(handler) = signature.handler else {
578                    return Err(Error::Validation(format!(
579                        "procedure `{}` does not have a WRITE handler",
580                        call.name
581                    )));
582                };
583                for arguments in arguments_by_row {
584                    self.check_query_control()?;
585                    handler(self.write_storage()?, &arguments)?;
586                }
587            }
588            if plan.returns.is_empty() {
589                return Ok(QueryResult {
590                    columns: Vec::new(),
591                    rows: Vec::new(),
592                });
593            }
594            match invocations.stage {
595                WriteProcedureStage::Initial => plan.procedure_calls.clear(),
596                WriteProcedureStage::PostWith => plan.post_with_procedure_calls.clear(),
597                WriteProcedureStage::PostSecondWith => plan.post_with_with_procedure_calls.clear(),
598            }
599        }
600        execute(&self.read_storage(), plan, params)
601    }
602
603    fn check_query_control(&self) -> Result<()> {
604        self.query_control
605            .as_ref()
606            .map_or(Ok(()), QueryControl::check)
607    }
608
609    fn execute_controlled_statement(
610        &mut self,
611        statement: Statement,
612        params: &Params,
613        control: QueryControl,
614    ) -> Result<QueryResult> {
615        debug_assert!(self.query_control.is_none());
616        self.query_control = Some(control);
617        let result = self.execute_statement(statement, params);
618        self.query_control = None;
619        result
620    }
621
622    fn write_storage(&mut self) -> Result<&mut dyn WritableStorage> {
623        self.backend.write()
624    }
625
626    fn execute_create(&mut self, create: CreateStatement, params: &Params) -> Result<QueryResult> {
627        let variable = create.node.variable.clone();
628        let properties = create_properties(&self.read_storage(), &create.node, params)?;
629        let node_id = self
630            .write_storage()?
631            .create_node(create.node.labels.clone(), properties)?;
632        let returns = create_returns(&create.returns, variable.as_deref())?;
633        let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
634        let row = returns
635            .iter()
636            .map(|item| {
637                project_created_item(
638                    &self.read_storage(),
639                    node_id,
640                    variable.as_deref(),
641                    item,
642                    params,
643                )
644            })
645            .collect::<Result<Vec<_>>>()?;
646
647        Ok(QueryResult {
648            columns,
649            rows: vec![Record { values: row }],
650        })
651    }
652
653    fn execute_create_relationship(
654        &mut self,
655        create: CreateRelationshipStatement,
656        params: &Params,
657    ) -> Result<QueryResult> {
658        let create_patterns = relationship_create_patterns(&create.pattern)?;
659        let relationship_variables = relationship_create_variables(&create_patterns);
660        let endpoint_variables = relationship_create_endpoint_variables(&create_patterns);
661        let endpoint_query = query_from_matches(
662            create.matches.clone(),
663            ReturnProjection::Items(element_id_return_items(&endpoint_variables)),
664        )?;
665        let endpoint_result = self.execute_plan(plan(endpoint_query)?, params)?;
666        let mut created_relationships = Vec::new();
667
668        for row in endpoint_result.rows {
669            self.check_query_control()?;
670            let ids = entity_ids_from_row(
671                &self.read_storage(),
672                &endpoint_result.columns,
673                &row,
674                &BTreeSet::new(),
675            )?;
676            let mut created_row = CreatedRelationshipRow::default();
677            let mut path_nodes = Vec::new();
678            let mut path_relationships = Vec::new();
679            if create.pattern.variable.is_some() {
680                let start_id =
681                    node_id_from_entities(&ids, &create_patterns[0].start_variable, "start")?;
682                path_nodes.push(start_id);
683            }
684
685            for create_pattern in &create_patterns {
686                self.check_query_control()?;
687                let start = node_id_from_entities(&ids, &create_pattern.start_variable, "start")?;
688                let end = node_id_from_entities(&ids, &create_pattern.end_variable, "end")?;
689                let (start, end) =
690                    relationship_write_endpoints(start, end, create_pattern.relationship.direction);
691                let relationship_type = relationship_create_type(&create_pattern.relationship)?;
692                let properties = relationship_properties_with_entities(
693                    &self.read_storage(),
694                    &ids,
695                    &create_pattern.relationship,
696                    params,
697                )?;
698                let relationship_id = self.write_storage()?.create_relationship(
699                    start,
700                    end,
701                    relationship_type,
702                    properties,
703                )?;
704                if let Some(variable) = &create_pattern.relationship.variable {
705                    created_row
706                        .relationships
707                        .insert(variable.clone(), relationship_id);
708                }
709                if create.pattern.variable.is_some() {
710                    let end_id = node_id_from_entities(&ids, &create_pattern.end_variable, "end")?;
711                    path_nodes.push(end_id);
712                    path_relationships.push(relationship_id);
713                }
714            }
715            if let Some(variable) = &create.pattern.variable {
716                created_row.path = Some(CreatedPath {
717                    variable: variable.clone(),
718                    nodes: path_nodes,
719                    relationships: path_relationships,
720                });
721            }
722
723            created_relationships.push(created_row);
724        }
725
726        let returns = create_relationship_returns(
727            &create.returns,
728            create.pattern.variable.as_deref(),
729            &relationship_variables,
730        )?;
731        let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
732        let rows = created_relationships
733            .iter()
734            .map(|relationship_ids| {
735                returns
736                    .iter()
737                    .map(|item| {
738                        project_created_relationships_item(
739                            &self.read_storage(),
740                            relationship_ids,
741                            item,
742                            params,
743                        )
744                    })
745                    .collect::<Result<Vec<_>>>()
746                    .map(|values| Record { values })
747            })
748            .collect::<Result<Vec<_>>>()?;
749
750        Ok(QueryResult { columns, rows })
751    }
752
753    fn execute_set(&mut self, set: SetStatement, params: &Params) -> Result<QueryResult> {
754        let relationship_variables = matched_relationship_variables(&set.matches);
755        let target_variables = set
756            .items
757            .iter()
758            .map(set_item_variable)
759            .collect::<BTreeSet<_>>();
760        let target_items = target_variables
761            .iter()
762            .map(|variable| ReturnItem {
763                expression: ReturnExpression::ElementId(variable.clone()),
764                alias: Some(variable.clone()),
765            })
766            .collect::<Vec<_>>();
767        let target_query =
768            query_from_matches(set.matches.clone(), ReturnProjection::Items(target_items))?;
769        let target_result = self.execute_plan(plan(target_query)?, params)?;
770        let mut matched_rows = Vec::<BTreeMap<String, EntityId>>::new();
771
772        for row in &target_result.rows {
773            self.check_query_control()?;
774            let mut ids = BTreeMap::new();
775            for (index, variable) in target_result.columns.iter().enumerate() {
776                match row.values.get(index) {
777                    Some(Value::String(external_id)) => {
778                        let entity_id = entity_id_from_external_id(
779                            &self.read_storage(),
780                            external_id,
781                            relationship_variables.contains(variable),
782                        )?;
783                        ids.insert(variable.clone(), entity_id);
784                    }
785                    Some(Value::Null) => {}
786                    _ => {
787                        return Err(Error::Validation(
788                            "SET currently supports node and relationship property assignments"
789                                .to_string(),
790                        ))
791                    }
792                }
793            }
794            matched_rows.push(ids);
795        }
796
797        for ids in &matched_rows {
798            self.check_query_control()?;
799            for item in &set.items {
800                let Some(entity_id) = ids.get(&set_item_variable(item)).copied() else {
801                    continue;
802                };
803                apply_set_item(self.write_storage()?, ids, entity_id, item, params)?;
804            }
805        }
806
807        let returns = set_returns(&set.returns, &target_variables)?;
808        let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
809        let rows = matched_rows
810            .iter()
811            .map(|ids| {
812                returns
813                    .iter()
814                    .map(|item| project_set_item(&self.read_storage(), ids, item, params))
815                    .collect::<Result<Vec<_>>>()
816                    .map(|values| Record { values })
817            })
818            .collect::<Result<Vec<_>>>()?;
819
820        Ok(QueryResult { columns, rows })
821    }
822
823    fn execute_foreach(
824        &mut self,
825        foreach: ForeachStatement,
826        params: &Params,
827    ) -> Result<QueryResult> {
828        let relationship_variables = matched_relationship_variables(&foreach.matches);
829        let mut target_variables = BTreeSet::<String>::new();
830        for item in &foreach.items {
831            target_variables.insert(set_item_variable(item));
832            target_variables.extend(collect_set_item_variables(item));
833        }
834        for variable in collect_expression_variables(&foreach.expression) {
835            target_variables.insert(variable);
836        }
837        target_variables.remove(&foreach.variable);
838
839        let target_items = target_variables
840            .iter()
841            .map(|variable| ReturnItem {
842                expression: ReturnExpression::ElementId(variable.clone()),
843                alias: Some(variable.clone()),
844            })
845            .collect::<Vec<_>>();
846        let target_query = query_from_matches(
847            foreach.matches.clone(),
848            ReturnProjection::Items(target_items),
849        )?;
850        let target_result = self.execute_plan(plan(target_query)?, params)?;
851        let mut matched_rows = Vec::<BTreeMap<String, EntityId>>::new();
852
853        for row in &target_result.rows {
854            self.check_query_control()?;
855            let ids = entity_ids_from_row(
856                &self.read_storage(),
857                &target_result.columns,
858                row,
859                &relationship_variables,
860            )?;
861            matched_rows.push(ids);
862        }
863
864        for ids in &matched_rows {
865            self.check_query_control()?;
866            let list_value = evaluate_write_expression_with_entities(
867                &self.read_storage(),
868                ids,
869                &foreach.expression,
870                params,
871            )?;
872            let Value::List(values) = list_value else {
873                return Err(Error::Validation(
874                    "FOREACH expression must evaluate to a list".to_string(),
875                ));
876            };
877
878            for value in values {
879                self.check_query_control()?;
880                for item in &foreach.items {
881                    let Some(entity_id) = ids.get(&set_item_variable(item)).copied() else {
882                        continue;
883                    };
884                    let item = substitute_set_item_value(item, &foreach.variable, &value);
885                    apply_set_item(self.write_storage()?, ids, entity_id, &item, params)?;
886                }
887            }
888        }
889
890        let returns = set_returns(&foreach.returns, &target_variables)?;
891        let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
892        let rows = matched_rows
893            .iter()
894            .map(|ids| {
895                returns
896                    .iter()
897                    .map(|item| project_set_item(&self.read_storage(), ids, item, params))
898                    .collect::<Result<Vec<_>>>()
899                    .map(|values| Record { values })
900            })
901            .collect::<Result<Vec<_>>>()?;
902
903        Ok(QueryResult { columns, rows })
904    }
905
906    fn execute_delete(&mut self, delete: DeleteStatement, params: &Params) -> Result<QueryResult> {
907        let relationship_variables = matched_relationship_variables(&delete.matches);
908        let target_items = delete
909            .variables
910            .iter()
911            .map(|variable| ReturnItem {
912                expression: ReturnExpression::ElementId(variable.clone()),
913                alias: Some(variable.clone()),
914            })
915            .collect::<Vec<_>>();
916        let target_query = query_from_matches(
917            delete.matches.clone(),
918            ReturnProjection::Items(target_items),
919        )?;
920        let target_result = self.execute_plan(plan(target_query)?, params)?;
921        let mut relationship_ids = BTreeSet::new();
922        let mut node_ids = BTreeSet::new();
923
924        for row in &target_result.rows {
925            self.check_query_control()?;
926            for (variable, value) in delete.variables.iter().zip(&row.values) {
927                let Value::String(external_id) = value else {
928                    continue;
929                };
930                if relationship_variables.contains(variable) {
931                    let relationship_id = self
932                        .read_storage()
933                        .relationship_by_external_id(external_id)
934                        .ok_or_else(|| {
935                            Error::Validation(format!(
936                                "DELETE relationship `{variable}` is no longer available"
937                            ))
938                        })?;
939                    relationship_ids.insert(relationship_id);
940                } else {
941                    let node_id = self
942                        .read_storage()
943                        .node_by_external_id(external_id)
944                        .ok_or_else(|| {
945                            Error::Validation(format!(
946                                "DELETE node `{variable}` is no longer available"
947                            ))
948                        })?;
949                    node_ids.insert(node_id);
950                }
951            }
952        }
953
954        for relationship_id in relationship_ids {
955            self.check_query_control()?;
956            self.write_storage()?.delete_relationship(relationship_id)?;
957        }
958        for node_id in node_ids {
959            self.check_query_control()?;
960            if delete.detach {
961                self.write_storage()?.detach_delete_node(node_id)?;
962            } else {
963                self.write_storage()?.delete_node(node_id)?;
964            }
965        }
966
967        Ok(QueryResult {
968            columns: Vec::new(),
969            rows: Vec::new(),
970        })
971    }
972
973    fn execute_remove(&mut self, remove: RemoveStatement, params: &Params) -> Result<QueryResult> {
974        let relationship_variables = matched_relationship_variables(&remove.matches);
975        let target_variables = remove
976            .items
977            .iter()
978            .map(remove_item_variable)
979            .collect::<BTreeSet<_>>();
980        let target_items = target_variables
981            .iter()
982            .map(|variable| ReturnItem {
983                expression: ReturnExpression::ElementId(variable.clone()),
984                alias: Some(variable.clone()),
985            })
986            .collect::<Vec<_>>();
987        let target_query = query_from_matches(
988            remove.matches.clone(),
989            ReturnProjection::Items(target_items),
990        )?;
991        let target_result = self.execute_plan(plan(target_query)?, params)?;
992        let mut matched_rows = Vec::<BTreeMap<String, EntityId>>::new();
993
994        for row in &target_result.rows {
995            self.check_query_control()?;
996            let mut ids = BTreeMap::new();
997            for (index, variable) in target_result.columns.iter().enumerate() {
998                match row.values.get(index) {
999                    Some(Value::String(external_id)) => {
1000                        let entity_id = entity_id_from_external_id(
1001                            &self.read_storage(),
1002                            external_id,
1003                            relationship_variables.contains(variable),
1004                        )?;
1005                        ids.insert(variable.clone(), entity_id);
1006                    }
1007                    Some(Value::Null) => {}
1008                    _ => {
1009                        return Err(Error::Validation(
1010                            "REMOVE currently supports node and relationship property removals"
1011                                .to_string(),
1012                        ))
1013                    }
1014                }
1015            }
1016            matched_rows.push(ids);
1017        }
1018
1019        for ids in &matched_rows {
1020            self.check_query_control()?;
1021            for item in &remove.items {
1022                let Some(entity_id) = ids.get(&remove_item_variable(item)).copied() else {
1023                    continue;
1024                };
1025                apply_remove_item(self.write_storage()?, entity_id, item)?;
1026            }
1027        }
1028
1029        let returns = set_returns(&remove.returns, &target_variables)?;
1030        let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
1031        let rows = matched_rows
1032            .iter()
1033            .map(|ids| {
1034                returns
1035                    .iter()
1036                    .map(|item| project_set_item(&self.read_storage(), ids, item, params))
1037                    .collect::<Result<Vec<_>>>()
1038                    .map(|values| Record { values })
1039            })
1040            .collect::<Result<Vec<_>>>()?;
1041
1042        Ok(QueryResult { columns, rows })
1043    }
1044
1045    fn execute_merge(&mut self, merge: MergeStatement, params: &Params) -> Result<QueryResult> {
1046        match merge {
1047            MergeStatement::Node {
1048                node,
1049                actions,
1050                returns,
1051            } => self.execute_merge_node(node, actions, returns, params),
1052            MergeStatement::Relationship {
1053                matches,
1054                pattern,
1055                actions,
1056                returns,
1057            } => self.execute_merge_relationship(matches, pattern, actions, returns, params),
1058        }
1059    }
1060
1061    fn execute_merge_node(
1062        &mut self,
1063        node: NodePattern,
1064        actions: Vec<MergeAction>,
1065        returns: ReturnProjection,
1066        params: &Params,
1067    ) -> Result<QueryResult> {
1068        let variable = node.variable.clone();
1069        let properties = create_properties(&self.read_storage(), &node, params)?;
1070        let (node_id, created) = match find_merge_node(&self.read_storage(), &node, &properties)? {
1071            Some(node_id) => (node_id, false),
1072            None => (
1073                self.write_storage()?
1074                    .create_node(node.labels.clone(), properties.clone())?,
1075                true,
1076            ),
1077        };
1078        if let Some(variable) = variable.as_deref() {
1079            apply_merge_actions(
1080                self.write_storage()?,
1081                EntityId::Node(node_id),
1082                variable,
1083                created,
1084                &actions,
1085                params,
1086            )?;
1087        } else if !actions.is_empty() {
1088            return Err(Error::Validation(
1089                "MERGE actions require a pattern variable".to_string(),
1090            ));
1091        }
1092        let returns = create_returns(&returns, variable.as_deref())?;
1093        let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
1094        let row = returns
1095            .iter()
1096            .map(|item| {
1097                project_created_item(
1098                    &self.read_storage(),
1099                    node_id,
1100                    variable.as_deref(),
1101                    item,
1102                    params,
1103                )
1104            })
1105            .collect::<Result<Vec<_>>>()?;
1106
1107        Ok(QueryResult {
1108            columns,
1109            rows: vec![Record { values: row }],
1110        })
1111    }
1112
1113    fn execute_merge_relationship(
1114        &mut self,
1115        matches: Vec<MatchClause>,
1116        pattern: Pattern,
1117        actions: Vec<MergeAction>,
1118        returns: ReturnProjection,
1119        params: &Params,
1120    ) -> Result<QueryResult> {
1121        let merge_pattern = relationship_create_pattern(&pattern)?;
1122        let start_variable = merge_pattern.start_variable.clone();
1123        let end_variable = merge_pattern.end_variable.clone();
1124        let relationship_variable = merge_pattern.relationship.variable.clone();
1125        let endpoint_variables =
1126            relationship_merge_endpoint_variables(&matches, &start_variable, &end_variable);
1127        let endpoint_query = query_from_matches(
1128            matches,
1129            ReturnProjection::Items(element_id_return_items(&endpoint_variables)),
1130        )?;
1131        let endpoint_result = self.execute_plan(plan(endpoint_query)?, params)?;
1132        let relationship_type = relationship_create_type(&merge_pattern.relationship)?;
1133        let mut relationship_ids = Vec::new();
1134
1135        for row in endpoint_result.rows {
1136            self.check_query_control()?;
1137            let ids = entity_ids_from_row(
1138                &self.read_storage(),
1139                &endpoint_result.columns,
1140                &row,
1141                &BTreeSet::new(),
1142            )?;
1143            let start = node_id_from_entities(&ids, &start_variable, "start")?;
1144            let end = node_id_from_entities(&ids, &end_variable, "end")?;
1145            let direction = merge_pattern.relationship.direction;
1146            let (start, end) = relationship_write_endpoints(start, end, direction);
1147            let properties = relationship_properties_with_entities(
1148                &self.read_storage(),
1149                &ids,
1150                &merge_pattern.relationship,
1151                params,
1152            )?;
1153            let (relationship_id, created) = match find_merge_relationship(
1154                &self.read_storage(),
1155                start,
1156                end,
1157                direction,
1158                &merge_pattern.relationship.types,
1159                &properties,
1160            )? {
1161                Some(relationship_id) => (relationship_id, false),
1162                None => (
1163                    self.write_storage()?.create_relationship(
1164                        start,
1165                        end,
1166                        relationship_type.clone(),
1167                        properties.clone(),
1168                    )?,
1169                    true,
1170                ),
1171            };
1172            if let Some(variable) = relationship_variable.as_deref() {
1173                apply_merge_actions(
1174                    self.write_storage()?,
1175                    EntityId::Relationship(relationship_id),
1176                    variable,
1177                    created,
1178                    &actions,
1179                    params,
1180                )?;
1181            } else if !actions.is_empty() {
1182                return Err(Error::Validation(
1183                    "MERGE actions require a relationship variable".to_string(),
1184                ));
1185            }
1186            relationship_ids.push(relationship_id);
1187        }
1188
1189        let relationship_variables = relationship_variable.iter().cloned().collect::<Vec<_>>();
1190        let returns = create_relationship_returns(&returns, None, &relationship_variables)?;
1191        let columns = returns.iter().map(create_return_column).collect::<Vec<_>>();
1192        let rows = relationship_ids
1193            .iter()
1194            .map(|relationship_id| {
1195                returns
1196                    .iter()
1197                    .map(|item| {
1198                        project_created_relationship_item(
1199                            &self.read_storage(),
1200                            *relationship_id,
1201                            relationship_variable.as_deref(),
1202                            item,
1203                            params,
1204                        )
1205                    })
1206                    .collect::<Result<Vec<_>>>()
1207                    .map(|values| Record { values })
1208            })
1209            .collect::<Result<Vec<_>>>()?;
1210
1211        Ok(QueryResult { columns, rows })
1212    }
1213}
1214
1215impl Transaction<'_> {
1216    pub fn query(&mut self, query: &str, params: Params) -> Result<QueryResult> {
1217        match self.state {
1218            TransactionHandleState::Active => {}
1219            TransactionHandleState::Failed(kind) => {
1220                return Err(Error::Transaction(kind));
1221            }
1222            TransactionHandleState::Completed => unreachable!("completed transaction is consumed"),
1223        }
1224
1225        self.check_control_state()?;
1226
1227        let control = QueryControl {
1228            deadline: self.deadline,
1229            cancellation_token: self.cancellation_token.clone(),
1230            max_query_memory_bytes: self.max_query_memory_bytes,
1231            query_memory_bytes: Cell::new(0),
1232        };
1233        let result = parse_statement(query).and_then(|statement| {
1234            if self.read_only && is_write_statement(&statement)? {
1235                return Err(Error::AccessMode);
1236            }
1237            self.graph
1238                .execute_controlled_statement(statement, &params, control)
1239        });
1240        if let Err(error) = &result {
1241            let kind = match error {
1242                Error::Transaction(
1243                    kind @ (TransactionErrorKind::ResourceLimit
1244                    | TransactionErrorKind::TimedOut
1245                    | TransactionErrorKind::Cancelled),
1246                ) => *kind,
1247                _ => TransactionErrorKind::RollbackOnly,
1248            };
1249            self.fail(kind);
1250            return result;
1251        }
1252        self.check_control_state()?;
1253        self.check_resource_limits(WorkspaceUsage::default())?;
1254        result
1255    }
1256
1257    /// Cancel this transaction. Rollback remains available.
1258    pub fn cancel(&mut self) {
1259        self.locally_cancelled = true;
1260        if self.state == TransactionHandleState::Active {
1261            self.fail(TransactionErrorKind::Cancelled);
1262        }
1263    }
1264
1265    /// Capture the transaction's current working state without touching disk.
1266    pub fn savepoint(&mut self) -> Result<Savepoint> {
1267        if let TransactionHandleState::Failed(kind) = self.state {
1268            return Err(Error::Transaction(kind));
1269        }
1270        self.check_control_state()?;
1271        let usage = self.savepoint_usage()?;
1272        self.check_resource_limits(usage)?;
1273        let backend = self.graph.backend.savepoint()?;
1274        let token = Savepoint {
1275            transaction_id: self.id,
1276            id: self.next_savepoint_id,
1277        };
1278        self.next_savepoint_id = self
1279            .next_savepoint_id
1280            .checked_add(1)
1281            .ok_or_else(|| Error::Execution("savepoint identifier space exhausted".to_owned()))?;
1282        self.savepoints.push(TransactionSavepoint {
1283            token,
1284            backend,
1285            usage,
1286        });
1287        self.sync_backend_workspace_limits()?;
1288        Ok(token)
1289    }
1290
1291    /// Restore a savepoint and discard every savepoint created after it.
1292    pub fn rollback_to(&mut self, savepoint: Savepoint) -> Result<()> {
1293        let index = self.savepoint_index(savepoint)?;
1294        self.graph
1295            .backend
1296            .rollback_to_savepoint(&self.savepoints[index].backend)?;
1297        self.savepoints.truncate(index + 1);
1298        self.state = TransactionHandleState::Active;
1299        self.sync_backend_workspace_limits()?;
1300        Ok(())
1301    }
1302
1303    /// Release a savepoint without changing the transaction's working state.
1304    pub fn release_savepoint(&mut self, savepoint: Savepoint) -> Result<()> {
1305        let index = self.savepoint_index(savepoint)?;
1306        self.savepoints.remove(index);
1307        self.sync_backend_workspace_limits()?;
1308        Ok(())
1309    }
1310
1311    fn savepoint_index(&self, savepoint: Savepoint) -> Result<usize> {
1312        if savepoint.transaction_id != self.id {
1313            return Err(Error::Transaction(TransactionErrorKind::InvalidSavepoint));
1314        }
1315        self.savepoints
1316            .iter()
1317            .position(|checkpoint| checkpoint.token == savepoint)
1318            .ok_or(Error::Transaction(TransactionErrorKind::InvalidSavepoint))
1319    }
1320
1321    fn check_control_state(&mut self) -> Result<()> {
1322        let failure = if self.locally_cancelled
1323            || self
1324                .cancellation_token
1325                .as_ref()
1326                .is_some_and(CancellationToken::is_cancelled)
1327        {
1328            Some(TransactionErrorKind::Cancelled)
1329        } else if self
1330            .deadline
1331            .is_some_and(|deadline| Instant::now() >= deadline)
1332        {
1333            Some(TransactionErrorKind::TimedOut)
1334        } else {
1335            None
1336        };
1337        if let Some(kind) = failure {
1338            self.fail(kind);
1339            Err(Error::Transaction(kind))
1340        } else {
1341            Ok(())
1342        }
1343    }
1344
1345    fn check_resource_limits(&mut self, additional: WorkspaceUsage) -> Result<()> {
1346        let usage = (|| {
1347            let mut usage = self
1348                .graph
1349                .backend
1350                .workspace_usage()?
1351                .checked_add(additional)?;
1352            usage = usage.checked_add(self.retained_savepoint_usage()?)?;
1353            Ok::<_, Error>(usage)
1354        })();
1355        let usage = match usage {
1356            Ok(usage) => usage,
1357            Err(error) => {
1358                self.fail(TransactionErrorKind::ResourceLimit);
1359                return Err(error);
1360            }
1361        };
1362        if self
1363            .max_workspace_bytes
1364            .is_some_and(|limit| usage.bytes > limit)
1365            || self.max_records.is_some_and(|limit| usage.records > limit)
1366        {
1367            self.fail(TransactionErrorKind::ResourceLimit);
1368            Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
1369        } else {
1370            Ok(())
1371        }
1372    }
1373
1374    fn retained_savepoint_usage(&self) -> Result<WorkspaceUsage> {
1375        self.savepoints
1376            .iter()
1377            .try_fold(WorkspaceUsage::default(), |usage, savepoint| {
1378                usage.checked_add(savepoint.usage)
1379            })
1380    }
1381
1382    fn savepoint_usage(&self) -> Result<WorkspaceUsage> {
1383        self.graph
1384            .backend
1385            .savepoint_usage()?
1386            .checked_add(WorkspaceUsage {
1387                bytes: std::mem::size_of::<TransactionSavepoint>(),
1388                records: 0,
1389            })
1390    }
1391
1392    fn sync_backend_workspace_limits(&mut self) -> Result<()> {
1393        let limits = (|| {
1394            let retained = self.retained_savepoint_usage()?;
1395            let max_workspace_bytes = self
1396                .max_workspace_bytes
1397                .map(|limit| {
1398                    limit
1399                        .checked_sub(retained.bytes)
1400                        .ok_or(Error::Transaction(TransactionErrorKind::ResourceLimit))
1401                })
1402                .transpose()?;
1403            let max_records = self
1404                .max_records
1405                .map(|limit| {
1406                    limit
1407                        .checked_sub(retained.records)
1408                        .ok_or(Error::Transaction(TransactionErrorKind::ResourceLimit))
1409                })
1410                .transpose()?;
1411            Ok::<_, Error>((max_workspace_bytes, max_records))
1412        })();
1413        let (max_workspace_bytes, max_records) = match limits {
1414            Ok(limits) => limits,
1415            Err(error) => {
1416                self.fail(TransactionErrorKind::ResourceLimit);
1417                return Err(error);
1418            }
1419        };
1420        if let Err(error) = self
1421            .graph
1422            .backend
1423            .set_workspace_limits(max_workspace_bytes, max_records)
1424        {
1425            self.fail(TransactionErrorKind::ResourceLimit);
1426            return Err(error);
1427        }
1428        Ok(())
1429    }
1430
1431    fn fail(&mut self, kind: TransactionErrorKind) {
1432        self.state = TransactionHandleState::Failed(kind);
1433        self.graph.backend.mark_transaction_failed();
1434    }
1435
1436    pub fn commit(mut self) -> Result<()> {
1437        if let TransactionHandleState::Failed(kind) = self.state {
1438            return Err(Error::Transaction(kind));
1439        }
1440        self.check_control_state()?;
1441        self.check_resource_limits(WorkspaceUsage::default())?;
1442        let result = self.graph.backend.commit_transaction();
1443        self.state = TransactionHandleState::Completed;
1444        result
1445    }
1446
1447    pub fn rollback(mut self) -> Result<()> {
1448        let result = self.graph.backend.rollback_transaction();
1449        self.state = TransactionHandleState::Completed;
1450        result
1451    }
1452}
1453
1454impl Drop for Transaction<'_> {
1455    fn drop(&mut self) {
1456        if self.state != TransactionHandleState::Completed {
1457            let _ = self.graph.backend.rollback_transaction();
1458            self.state = TransactionHandleState::Completed;
1459        }
1460    }
1461}
1462
1463fn is_write_statement(statement: &Statement) -> Result<bool> {
1464    fn query_writes(query: &Query) -> Result<bool> {
1465        query
1466            .procedure_calls
1467            .iter()
1468            .chain(query.post_with_procedure_calls.iter())
1469            .chain(query.post_with_with_procedure_calls.iter())
1470            .try_fold(false, |writes, call| {
1471                Ok(writes || resolve_procedure(&call.name)?.mode == ProcedureMode::Write)
1472            })
1473    }
1474
1475    match statement {
1476        Statement::Single(query) => query_writes(query),
1477        Statement::Union { first, parts } => {
1478            if query_writes(first)? {
1479                return Ok(true);
1480            }
1481            for part in parts {
1482                if query_writes(&part.query)? {
1483                    return Ok(true);
1484                }
1485            }
1486            Ok(false)
1487        }
1488        _ => Ok(true),
1489    }
1490}
1491
1492fn create_properties(
1493    storage: &dyn StorageInterface,
1494    node: &NodePattern,
1495    params: &Params,
1496) -> Result<Properties> {
1497    let ids = BTreeMap::new();
1498    node.properties
1499        .iter()
1500        .map(|property| {
1501            evaluate_write_expression_with_entities(storage, &ids, &property.expression, params)
1502                .map(|value| (property.key.clone(), value))
1503        })
1504        .collect()
1505}
1506
1507#[cfg(test)]
1508mod transaction_option_tests {
1509    use std::cell::Cell;
1510
1511    use super::*;
1512
1513    struct CancellingStorage {
1514        checks: Cell<usize>,
1515        cancel_at: usize,
1516    }
1517
1518    impl StorageInterface for CancellingStorage {
1519        fn check_query_control(&self) -> Result<()> {
1520            let checks = self.checks.get() + 1;
1521            self.checks.set(checks);
1522            if checks >= self.cancel_at {
1523                Err(Error::Transaction(TransactionErrorKind::Cancelled))
1524            } else {
1525                Ok(())
1526            }
1527        }
1528
1529        fn node_ids(&self) -> Vec<NodeId> {
1530            Vec::new()
1531        }
1532
1533        fn relationship_ids(&self) -> Vec<RelationshipId> {
1534            Vec::new()
1535        }
1536
1537        fn node(&self, _id: NodeId) -> Option<&crate::graph_model::Node> {
1538            None
1539        }
1540
1541        fn relationship(&self, _id: RelationshipId) -> Option<&crate::graph_model::Relationship> {
1542            None
1543        }
1544
1545        fn outgoing_relationships(&self, _id: NodeId) -> &[RelationshipId] {
1546            &[]
1547        }
1548
1549        fn incoming_relationships(&self, _id: NodeId) -> &[RelationshipId] {
1550            &[]
1551        }
1552
1553        fn nodes_with_label(&self, _label: &str) -> &[NodeId] {
1554            &[]
1555        }
1556
1557        fn node_by_external_id(&self, _external_id: &str) -> Option<NodeId> {
1558            None
1559        }
1560
1561        fn relationship_by_external_id(&self, _external_id: &str) -> Option<RelationshipId> {
1562            None
1563        }
1564
1565        fn label_tokens(&self) -> Vec<String> {
1566            Vec::new()
1567        }
1568
1569        fn relationship_type_tokens(&self) -> Vec<String> {
1570            Vec::new()
1571        }
1572
1573        fn property_key_tokens(&self) -> Vec<String> {
1574            Vec::new()
1575        }
1576    }
1577
1578    #[test]
1579    fn read_procedures_use_public_api_and_transaction_read_view() {
1580        let home = tempfile::tempdir().unwrap();
1581        let database = home.path().join("data/databases/neo4j");
1582        Neo4jStorage::initialize_if_empty(&database).unwrap();
1583        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
1584
1585        let empty = graph.query("CALL db.labels()", Params::new()).unwrap();
1586        assert_eq!(empty.columns, ["label"]);
1587        assert!(empty.rows.is_empty());
1588        let initial_info = graph.query("CALL db.info()", Params::new()).unwrap();
1589        assert_eq!(initial_info.columns, ["id", "name", "creationDate"]);
1590        assert_eq!(initial_info.rows.len(), 1);
1591        assert_eq!(
1592            initial_info.rows[0].values[1],
1593            Value::String("neo4j".to_owned())
1594        );
1595        let post_with_ping = graph
1596            .query(
1597                "UNWIND [1, 2] AS n WITH n \
1598                 CALL db.ping() YIELD success RETURN n, success",
1599                Params::new(),
1600            )
1601            .unwrap();
1602        assert_eq!(post_with_ping.columns, ["n", "success"]);
1603        assert_eq!(post_with_ping.rows.len(), 2);
1604
1605        let mut transaction = graph.transaction().unwrap();
1606        transaction
1607            .query("CREATE (:Start {id: 1, name: 'start'})", Params::new())
1608            .unwrap();
1609        transaction
1610            .query("CREATE (:Finish {id: 2})", Params::new())
1611            .unwrap();
1612        transaction
1613            .query(
1614                "MATCH (a:Start {id: 1}), (b:Finish {id: 2}) \
1615                 CREATE (a)-[:CONNECTS]->(b)",
1616                Params::new(),
1617            )
1618            .unwrap();
1619
1620        let match_after_call = transaction
1621            .query(
1622                "CALL db.ping() YIELD success MATCH (start:Start) \
1623                 RETURN start.id, success",
1624                Params::new(),
1625            )
1626            .unwrap();
1627        assert_eq!(match_after_call.columns, ["start.id", "success"]);
1628        assert_eq!(
1629            match_after_call.rows[0].values,
1630            [Value::Integer(1), Value::Boolean(true)]
1631        );
1632
1633        let labels = transaction
1634            .query("CALL db.labels() YIELD label RETURN label", Params::new())
1635            .unwrap();
1636        assert_eq!(labels.columns, ["label"]);
1637        assert_eq!(
1638            labels
1639                .rows
1640                .iter()
1641                .map(|row| row.values[0].clone())
1642                .collect::<Vec<_>>(),
1643            [
1644                Value::String("Start".to_owned()),
1645                Value::String("Finish".to_owned())
1646            ]
1647        );
1648
1649        let relationship_types = transaction
1650            .query("CALL db.relationshipTypes()", Params::new())
1651            .unwrap();
1652        assert_eq!(relationship_types.columns, ["relationshipType"]);
1653        assert_eq!(
1654            relationship_types.rows[0].values,
1655            [Value::String("CONNECTS".to_owned())]
1656        );
1657
1658        let property_keys = transaction
1659            .query("CALL db.propertyKeys()", Params::new())
1660            .unwrap();
1661        assert_eq!(property_keys.columns, ["propertyKey"]);
1662        assert_eq!(
1663            property_keys
1664                .rows
1665                .iter()
1666                .map(|row| row.values[0].clone())
1667                .collect::<Vec<_>>(),
1668            [
1669                Value::String("id".to_owned()),
1670                Value::String("name".to_owned())
1671            ]
1672        );
1673
1674        let node_schema = transaction
1675            .query("CALL db.schema.nodeTypeProperties()", Params::new())
1676            .unwrap();
1677        assert_eq!(
1678            node_schema.columns,
1679            [
1680                "nodeType",
1681                "nodeLabels",
1682                "propertyName",
1683                "propertyTypes",
1684                "mandatory"
1685            ]
1686        );
1687        assert_eq!(node_schema.rows.len(), 3);
1688        assert!(node_schema.rows.iter().any(|row| {
1689            row.values
1690                == [
1691                    Value::String(":`Start`".to_owned()),
1692                    Value::List(vec![Value::String("Start".to_owned())]),
1693                    Value::String("name".to_owned()),
1694                    Value::List(vec![Value::String("String".to_owned())]),
1695                    Value::Boolean(true),
1696                ]
1697        }));
1698
1699        let relationship_schema = transaction
1700            .query("CALL db.schema.relTypeProperties()", Params::new())
1701            .unwrap();
1702        assert_eq!(
1703            relationship_schema.columns,
1704            ["relType", "propertyName", "propertyTypes", "mandatory"]
1705        );
1706        assert_eq!(
1707            relationship_schema.rows[0].values,
1708            [
1709                Value::String(":`CONNECTS`".to_owned()),
1710                Value::Null,
1711                Value::Null,
1712                Value::Boolean(false),
1713            ]
1714        );
1715
1716        let visualization = transaction
1717            .query("CALL db.schema.visualization()", Params::new())
1718            .unwrap();
1719        assert_eq!(visualization.columns, ["nodes", "relationships"]);
1720        let [Value::List(virtual_nodes), Value::List(virtual_relationships)] =
1721            visualization.rows[0].values.as_slice()
1722        else {
1723            panic!("expected virtual schema graph lists")
1724        };
1725        assert_eq!(virtual_nodes.len(), 2);
1726        assert_eq!(virtual_relationships.len(), 1);
1727        assert!(virtual_nodes.iter().all(|value| {
1728            matches!(value, Value::Node(node)
1729                if node.properties["indexes"] == Value::List(Vec::new())
1730                    && node.properties["constraints"] == Value::List(Vec::new()))
1731        }));
1732
1733        let before_delete = transaction.savepoint().unwrap();
1734        transaction
1735            .query("MATCH (n) DETACH DELETE n", Params::new())
1736            .unwrap();
1737        assert!(transaction
1738            .query("CALL db.labels()", Params::new())
1739            .unwrap()
1740            .rows
1741            .is_empty());
1742        assert!(transaction
1743            .query("CALL db.relationshipTypes()", Params::new())
1744            .unwrap()
1745            .rows
1746            .is_empty());
1747        assert!(transaction
1748            .query("CALL db.schema.nodeTypeProperties()", Params::new())
1749            .unwrap()
1750            .rows
1751            .is_empty());
1752        assert!(transaction
1753            .query("CALL db.schema.relTypeProperties()", Params::new())
1754            .unwrap()
1755            .rows
1756            .is_empty());
1757        assert_eq!(
1758            transaction
1759                .query("CALL db.schema.visualization()", Params::new())
1760                .unwrap()
1761                .rows[0]
1762                .values,
1763            [Value::List(Vec::new()), Value::List(Vec::new())]
1764        );
1765        assert_eq!(
1766            transaction
1767                .query("CALL db.propertyKeys()", Params::new())
1768                .unwrap()
1769                .rows
1770                .len(),
1771            2
1772        );
1773        transaction.rollback_to(before_delete).unwrap();
1774        transaction.commit().unwrap();
1775        drop(graph);
1776
1777        let mut reopened = Graph::open_neo4j(&database).unwrap();
1778        let ping = reopened.query("CALL db.ping()", Params::new()).unwrap();
1779        assert_eq!(ping.rows[0].values, [Value::Boolean(true)]);
1780        assert_eq!(
1781            reopened
1782                .query("CALL db.info()", Params::new())
1783                .unwrap()
1784                .rows[0],
1785            initial_info.rows[0]
1786        );
1787        assert_eq!(
1788            reopened
1789                .query("CALL db.labels()", Params::new())
1790                .unwrap()
1791                .rows
1792                .len(),
1793            2
1794        );
1795        assert_eq!(
1796            reopened
1797                .query("CALL db.propertyKeys()", Params::new())
1798                .unwrap()
1799                .rows
1800                .len(),
1801            2
1802        );
1803        assert_eq!(
1804            reopened
1805                .query("CALL db.relationshipTypes()", Params::new())
1806                .unwrap()
1807                .rows[0]
1808                .values,
1809            [Value::String("CONNECTS".to_owned())]
1810        );
1811    }
1812
1813    #[test]
1814    fn database_info_keeps_store_identity_when_the_directory_is_copied() {
1815        fn copy_directory(source: &Path, target: &Path) {
1816            std::fs::create_dir_all(target).unwrap();
1817            for entry in std::fs::read_dir(source).unwrap() {
1818                let entry = entry.unwrap();
1819                let source_path = entry.path();
1820                let target_path = target.join(entry.file_name());
1821                if entry.file_type().unwrap().is_dir() {
1822                    copy_directory(&source_path, &target_path);
1823                } else {
1824                    std::fs::copy(source_path, target_path).unwrap();
1825                }
1826            }
1827        }
1828
1829        let home = tempfile::tempdir().unwrap();
1830        let source = home.path().join("data/databases/original");
1831        Neo4jStorage::initialize_if_empty(&source).unwrap();
1832        let source_info = {
1833            let mut graph = Graph::open_neo4j(&source).unwrap();
1834            graph
1835                .query("CALL db.info()", Params::new())
1836                .unwrap()
1837                .rows
1838                .remove(0)
1839        };
1840
1841        let copied = home.path().join("data/databases/copied");
1842        copy_directory(&source, &copied);
1843        let copied_info = {
1844            let mut graph = Graph::open_neo4j(&copied).unwrap();
1845            graph
1846                .query("CALL db.info()", Params::new())
1847                .unwrap()
1848                .rows
1849                .remove(0)
1850        };
1851
1852        assert_eq!(source_info.values[0], copied_info.values[0]);
1853        assert_eq!(source_info.values[2], copied_info.values[2]);
1854        assert_eq!(source_info.values[1], Value::String("original".to_owned()));
1855        assert_eq!(copied_info.values[1], Value::String("copied".to_owned()));
1856    }
1857
1858    #[test]
1859    fn token_creation_procedures_follow_transaction_and_reader_semantics() {
1860        let home = tempfile::tempdir().unwrap();
1861        let database = home.path().join("data/databases/neo4j");
1862        Neo4jStorage::initialize_if_empty(&database).unwrap();
1863        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
1864
1865        let result = graph
1866            .query("CALL db.createLabel('Reserved')", Params::new())
1867            .unwrap();
1868        assert!(result.columns.is_empty());
1869        assert!(result.rows.is_empty());
1870        let projected = graph
1871            .query(
1872                "CALL db.createLabel('Projected') RETURN 1 AS value",
1873                Params::new(),
1874            )
1875            .unwrap();
1876        assert_eq!(projected.columns, ["value"]);
1877        assert_eq!(projected.rows[0].values, [Value::Integer(1)]);
1878        graph
1879            .query("CALL db.createLabel('Reserved')", Params::new())
1880            .unwrap();
1881        graph
1882            .query(
1883                "CALL db.createRelationshipType('RESERVED_FOR')",
1884                Params::new(),
1885            )
1886            .unwrap();
1887        graph
1888            .query(
1889                "CALL db.createProperty($name)",
1890                Params::from([("name".to_owned(), Value::String("reservedKey".to_owned()))]),
1891            )
1892            .unwrap();
1893
1894        assert!(graph
1895            .query("CALL db.labels()", Params::new())
1896            .unwrap()
1897            .rows
1898            .is_empty());
1899        assert!(graph
1900            .query("CALL db.relationshipTypes()", Params::new())
1901            .unwrap()
1902            .rows
1903            .is_empty());
1904        assert_eq!(
1905            graph
1906                .query("CALL db.propertyKeys()", Params::new())
1907                .unwrap()
1908                .rows[0]
1909                .values,
1910            [Value::String("reservedKey".to_owned())]
1911        );
1912
1913        let mut transaction = graph.transaction().unwrap();
1914        let before_tokens = transaction.savepoint().unwrap();
1915        transaction
1916            .query("CALL db.createProperty('rolledBackKey')", Params::new())
1917            .unwrap();
1918        assert_eq!(
1919            transaction
1920                .query("CALL db.propertyKeys()", Params::new())
1921                .unwrap()
1922                .rows
1923                .len(),
1924            2
1925        );
1926        transaction.rollback_to(before_tokens).unwrap();
1927        assert_eq!(
1928            transaction
1929                .query("CALL db.propertyKeys()", Params::new())
1930                .unwrap()
1931                .rows
1932                .len(),
1933            1
1934        );
1935        transaction.commit().unwrap();
1936        drop(graph);
1937
1938        let mut reopened = Graph::open_neo4j(&database).unwrap();
1939        assert_eq!(
1940            reopened
1941                .query("CALL db.propertyKeys()", Params::new())
1942                .unwrap()
1943                .rows
1944                .len(),
1945            1
1946        );
1947        assert!(matches!(
1948            reopened.query("CALL db.createProperty('denied')", Params::new()),
1949            Err(Error::UnsupportedWriteQuery(_))
1950                | Err(Error::Transaction(TransactionErrorKind::NotActive))
1951        ));
1952    }
1953
1954    #[test]
1955    fn write_procedures_execute_once_per_input_row() {
1956        let home = tempfile::tempdir().unwrap();
1957        let database = home.path().join("data/databases/neo4j");
1958        Neo4jStorage::initialize_if_empty(&database).unwrap();
1959        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
1960
1961        let batch = graph
1962            .query(
1963                "UNWIND ['batchOne', 'batchTwo'] AS name \
1964                 CALL db.createProperty(name) RETURN name",
1965                Params::new(),
1966            )
1967            .unwrap();
1968        assert_eq!(batch.columns, ["name"]);
1969        assert_eq!(
1970            batch
1971                .rows
1972                .iter()
1973                .map(|row| row.values[0].clone())
1974                .collect::<Vec<_>>(),
1975            [
1976                Value::String("batchOne".to_owned()),
1977                Value::String("batchTwo".to_owned()),
1978            ]
1979        );
1980
1981        graph
1982            .query("CREATE (:TokenSource {name: 'fromMatch'})", Params::new())
1983            .unwrap();
1984        let matched = graph
1985            .query(
1986                "MATCH (source:TokenSource) CALL db.createProperty(source.name) \
1987                 RETURN source.name",
1988                Params::new(),
1989            )
1990            .unwrap();
1991        assert_eq!(
1992            matched.rows[0].values,
1993            [Value::String("fromMatch".to_owned())]
1994        );
1995        let empty = graph
1996            .query(
1997                "UNWIND [] AS name CALL db.createProperty('emptyInput') RETURN name",
1998                Params::new(),
1999            )
2000            .unwrap();
2001        assert!(empty.rows.is_empty());
2002
2003        let property_keys = graph
2004            .query("CALL db.propertyKeys()", Params::new())
2005            .unwrap()
2006            .rows
2007            .into_iter()
2008            .map(|row| row.values[0].clone())
2009            .collect::<Vec<_>>();
2010        for expected in ["batchOne", "batchTwo", "name", "fromMatch"] {
2011            assert!(property_keys.contains(&Value::String(expected.to_owned())));
2012        }
2013        assert!(!property_keys.contains(&Value::String("emptyInput".to_owned())));
2014
2015        let mut transaction = graph.transaction().unwrap();
2016        transaction
2017            .query(
2018                "UNWIND ['rollbackOne', 'rollbackTwo'] AS name \
2019                 CALL db.createProperty(name) RETURN name",
2020                Params::new(),
2021            )
2022            .unwrap();
2023        transaction.rollback().unwrap();
2024
2025        let property_keys = graph
2026            .query("CALL db.propertyKeys()", Params::new())
2027            .unwrap()
2028            .rows
2029            .into_iter()
2030            .map(|row| row.values[0].clone())
2031            .collect::<Vec<_>>();
2032        assert!(!property_keys.contains(&Value::String("rollbackOne".to_owned())));
2033        assert!(!property_keys.contains(&Value::String("rollbackTwo".to_owned())));
2034    }
2035
2036    #[test]
2037    fn read_only_transaction_options_reject_writes() {
2038        let home = tempfile::tempdir().unwrap();
2039        let database = home.path().join("data/databases/neo4j");
2040        Neo4jStorage::initialize_if_empty(&database).unwrap();
2041        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2042
2043        {
2044            let mut transaction = graph
2045                .transaction_with_options(TransactionOptions {
2046                    read_only: true,
2047                    ..TransactionOptions::default()
2048                })
2049                .unwrap();
2050            assert_eq!(
2051                transaction.query("RETURN 1", Params::new()).unwrap().rows[0].values,
2052                [Value::Integer(1)]
2053            );
2054            assert!(matches!(
2055                transaction.query("CREATE (:ReadOnlyDenied)", Params::new()),
2056                Err(Error::AccessMode)
2057            ));
2058        }
2059
2060        let result = graph
2061            .query("MATCH (n:ReadOnlyDenied) RETURN n", Params::new())
2062            .unwrap();
2063        assert!(result.rows.is_empty());
2064    }
2065
2066    #[test]
2067    fn write_procedures_execute_after_supported_with_scopes() {
2068        let home = tempfile::tempdir().unwrap();
2069        let database = home.path().join("data/databases/neo4j");
2070        Neo4jStorage::initialize_if_empty(&database).unwrap();
2071        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2072
2073        let first_scope = graph
2074            .query(
2075                "UNWIND ['afterWithOne', 'afterWithTwo'] AS name WITH name \
2076                 CALL db.createProperty(name) RETURN name",
2077                Params::new(),
2078            )
2079            .unwrap();
2080        assert_eq!(first_scope.rows.len(), 2);
2081
2082        let second_scope = graph
2083            .query(
2084                "UNWIND ['afterSecondWith'] AS name WITH name WITH name \
2085                 CALL db.createProperty(name) RETURN name",
2086                Params::new(),
2087            )
2088            .unwrap();
2089        assert_eq!(second_scope.rows.len(), 1);
2090
2091        let mut transaction = graph.transaction().unwrap();
2092        transaction
2093            .query(
2094                "UNWIND ['lateRollbackOne', 'lateRollbackTwo'] AS name WITH name \
2095                 CALL db.createProperty(name) RETURN name",
2096                Params::new(),
2097            )
2098            .unwrap();
2099        transaction.rollback().unwrap();
2100
2101        for query in [
2102            "CALL db.ping() YIELD success WITH success \
2103             CALL db.createProperty('mixedMode') RETURN success",
2104            "CALL db.createProperty('firstStage') WITH 1 AS n \
2105             CALL db.createProperty('secondStage') RETURN n",
2106        ] {
2107            assert!(matches!(
2108                graph.query(query, Params::new()),
2109                Err(Error::Validation(_))
2110            ));
2111        }
2112
2113        let property_keys = graph
2114            .query("CALL db.propertyKeys()", Params::new())
2115            .unwrap()
2116            .rows
2117            .into_iter()
2118            .map(|row| row.values[0].clone())
2119            .collect::<Vec<_>>();
2120        for expected in ["afterWithOne", "afterWithTwo", "afterSecondWith"] {
2121            assert!(property_keys.contains(&Value::String(expected.to_owned())));
2122        }
2123        for absent in [
2124            "lateRollbackOne",
2125            "lateRollbackTwo",
2126            "mixedMode",
2127            "firstStage",
2128            "secondStage",
2129        ] {
2130            assert!(!property_keys.contains(&Value::String(absent.to_owned())));
2131        }
2132    }
2133
2134    #[test]
2135    fn token_creation_procedures_validate_arguments_without_committing_artifacts() {
2136        let home = tempfile::tempdir().unwrap();
2137        let database = home.path().join("data/databases/neo4j");
2138        Neo4jStorage::initialize_if_empty(&database).unwrap();
2139        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2140
2141        for query in [
2142            "CALL db.createProperty()",
2143            "CALL db.createProperty(null)",
2144            "CALL db.createProperty(1)",
2145            "CALL db.createProperty('')",
2146        ] {
2147            assert!(graph.query(query, Params::new()).is_err(), "{query}");
2148        }
2149        assert!(graph
2150            .query("CALL db.propertyKeys()", Params::new())
2151            .unwrap()
2152            .rows
2153            .is_empty());
2154    }
2155
2156    #[test]
2157    fn concurrent_token_procedures_use_existing_mvcc_conflict_rules() {
2158        let home = tempfile::tempdir().unwrap();
2159        let database = home.path().join("data/databases/neo4j");
2160        Neo4jStorage::initialize_if_empty(&database).unwrap();
2161        let mut first_graph = Graph::open_neo4j_writable(&database).unwrap();
2162        let mut second_graph = Graph::open_neo4j_writable(&database).unwrap();
2163
2164        let mut first = first_graph.transaction().unwrap();
2165        let mut second = second_graph.transaction().unwrap();
2166        first
2167            .query("CALL db.createProperty('firstKey')", Params::new())
2168            .unwrap();
2169        second
2170            .query("CALL db.createProperty('secondKey')", Params::new())
2171            .unwrap();
2172        first.commit().unwrap();
2173        assert!(matches!(
2174            second.commit(),
2175            Err(Error::Transaction(TransactionErrorKind::Conflict))
2176        ));
2177
2178        let mut third = first_graph.transaction().unwrap();
2179        let mut fourth = second_graph.transaction().unwrap();
2180        third
2181            .query("CALL db.createLabel('ConcurrentLabel')", Params::new())
2182            .unwrap();
2183        fourth
2184            .query("CALL db.createProperty('disjointKey')", Params::new())
2185            .unwrap();
2186        third.commit().unwrap();
2187        fourth.commit().unwrap();
2188
2189        drop(first_graph);
2190        drop(second_graph);
2191        let mut reopened = Graph::open_neo4j(&database).unwrap();
2192        let keys = reopened
2193            .query("CALL db.propertyKeys()", Params::new())
2194            .unwrap();
2195        assert_eq!(
2196            keys.rows
2197                .into_iter()
2198                .map(|row| row.values[0].clone())
2199                .collect::<Vec<_>>(),
2200            [
2201                Value::String("firstKey".to_owned()),
2202                Value::String("disjointKey".to_owned())
2203            ]
2204        );
2205    }
2206
2207    #[test]
2208    fn token_procedure_commit_failure_leaves_no_artifacts() {
2209        let home = tempfile::tempdir().unwrap();
2210        let database = home.path().join("data/databases/neo4j");
2211        Neo4jStorage::initialize_if_empty(&database).unwrap();
2212        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2213
2214        crate::neo4j_storage::fail_next_commit_after_patch(0);
2215        assert!(graph
2216            .query("CALL db.createProperty('notCommitted')", Params::new())
2217            .is_err());
2218        drop(graph);
2219
2220        assert!(!database.join(".littlegraph-write-journal").exists());
2221        let mut reopened = Graph::open_neo4j(&database).unwrap();
2222        assert!(reopened
2223            .query("CALL db.propertyKeys()", Params::new())
2224            .unwrap()
2225            .rows
2226            .is_empty());
2227    }
2228
2229    #[test]
2230    fn api_comparison_scans_propagate_cancellation() {
2231        let storage = CancellingStorage {
2232            checks: Cell::new(0),
2233            cancel_at: 2,
2234        };
2235        let values = (0..QUERY_CONTROL_COMPARISON_BATCH * 3).collect::<Vec<_>>();
2236        assert!(matches!(
2237            controlled_position(&storage, &values, |value| *value == usize::MAX),
2238            Err(Error::Transaction(TransactionErrorKind::Cancelled))
2239        ));
2240        assert_eq!(storage.checks.get(), storage.cancel_at);
2241
2242        let storage = CancellingStorage {
2243            checks: Cell::new(0),
2244            cancel_at: 2,
2245        };
2246        let list = Value::List(
2247            (0..QUERY_CONTROL_COMPARISON_BATCH * 3)
2248                .map(|value| Value::Integer(value as i64))
2249                .collect(),
2250        );
2251        assert!(matches!(
2252            evaluate_write_in_predicate(list, Value::Integer(-1), Some(&storage)),
2253            Err(Error::Transaction(TransactionErrorKind::Cancelled))
2254        ));
2255        assert_eq!(storage.checks.get(), storage.cancel_at);
2256
2257        let storage = CancellingStorage {
2258            checks: Cell::new(0),
2259            cancel_at: 1,
2260        };
2261        let mut rows = vec![Record {
2262            values: vec![Value::Integer(1)],
2263        }];
2264        assert!(matches!(
2265            deduplicate_rows(&storage, &mut rows),
2266            Err(Error::Transaction(TransactionErrorKind::Cancelled))
2267        ));
2268        assert_eq!(storage.checks.get(), storage.cancel_at);
2269
2270        let storage = CancellingStorage {
2271            checks: Cell::new(0),
2272            cancel_at: 2,
2273        };
2274        assert!(matches!(
2275            evaluate_write_range_value(
2276                Value::Integer(1),
2277                Value::Integer(1_000_000),
2278                None,
2279                Some(&storage),
2280            ),
2281            Err(Error::Transaction(TransactionErrorKind::Cancelled))
2282        ));
2283        assert_eq!(storage.checks.get(), storage.cancel_at);
2284
2285        let storage = CancellingStorage {
2286            checks: Cell::new(0),
2287            cancel_at: 1,
2288        };
2289        let item = ReturnItem {
2290            expression: ReturnExpression::Scalar(Expression::Literal(Value::Integer(1))),
2291            alias: None,
2292        };
2293        assert!(matches!(
2294            project_created_item(&storage, 0, None, &item, &Params::new()),
2295            Err(Error::Transaction(TransactionErrorKind::Cancelled))
2296        ));
2297        assert_eq!(storage.checks.get(), storage.cancel_at);
2298    }
2299
2300    #[test]
2301    fn retry_helper_does_not_retry_cancellation_or_execution_errors() {
2302        let home = tempfile::tempdir().unwrap();
2303        let database = home.path().join("data/databases/neo4j");
2304        Neo4jStorage::initialize_if_empty(&database).unwrap();
2305        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2306        let token = CancellationToken::new();
2307        token.cancel();
2308        let attempts = Cell::new(0);
2309        let error = graph
2310            .run_transaction_with_options(
2311                TransactionOptions {
2312                    cancellation_token: Some(token),
2313                    ..TransactionOptions::default()
2314                },
2315                3,
2316                |transaction| {
2317                    attempts.set(attempts.get() + 1);
2318                    transaction.query("MATCH (n) RETURN n", Params::new())?;
2319                    Ok(())
2320                },
2321            )
2322            .unwrap_err();
2323        assert!(matches!(
2324            error,
2325            Error::Transaction(TransactionErrorKind::Cancelled)
2326        ));
2327        assert_eq!(attempts.get(), 1);
2328
2329        let attempts = Cell::new(0);
2330        let error = graph
2331            .run_transaction(3, |transaction| {
2332                attempts.set(attempts.get() + 1);
2333                transaction.query("THIS IS NOT CYPHER", Params::new())?;
2334                Ok(())
2335            })
2336            .unwrap_err();
2337        assert!(matches!(error, Error::Parse(_)));
2338        assert_eq!(attempts.get(), 1);
2339    }
2340
2341    #[test]
2342    fn workspace_limits_accept_exact_boundaries_and_charge_savepoints() {
2343        let home = tempfile::tempdir().unwrap();
2344        let database = home.path().join("data/databases/neo4j");
2345        Neo4jStorage::initialize_if_empty(&database).unwrap();
2346        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2347
2348        let (base_usage, usage, savepoint_usage) = {
2349            let mut transaction = graph.transaction().unwrap();
2350            let base_usage = transaction.graph.backend.workspace_usage().unwrap();
2351            transaction
2352                .query("CREATE (:BudgetBoundary {value: 1})", Params::new())
2353                .unwrap();
2354            let usage = transaction.graph.backend.workspace_usage().unwrap();
2355            let savepoint_usage = transaction.savepoint_usage().unwrap();
2356            transaction.rollback().unwrap();
2357            (base_usage, usage, savepoint_usage)
2358        };
2359        assert!(base_usage.bytes > 0);
2360        assert_eq!(base_usage.records, 0);
2361        assert!(usage.bytes > 0);
2362        assert!(usage.records > 0);
2363
2364        graph
2365            .transaction_with_options(TransactionOptions {
2366                max_workspace_bytes: Some(base_usage.bytes),
2367                ..TransactionOptions::default()
2368            })
2369            .unwrap()
2370            .commit()
2371            .unwrap();
2372        assert!(matches!(
2373            graph.transaction_with_options(TransactionOptions {
2374                max_workspace_bytes: Some(base_usage.bytes - 1),
2375                ..TransactionOptions::default()
2376            }),
2377            Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2378        ));
2379
2380        {
2381            let mut transaction = graph
2382                .transaction_with_options(TransactionOptions {
2383                    max_workspace_bytes: Some(usage.bytes),
2384                    max_records: Some(usage.records),
2385                    ..TransactionOptions::default()
2386                })
2387                .unwrap();
2388            transaction
2389                .query("CREATE (:BudgetBoundary {value: 1})", Params::new())
2390                .unwrap();
2391            transaction.rollback().unwrap();
2392        }
2393
2394        for options in [
2395            TransactionOptions {
2396                max_workspace_bytes: Some(usage.bytes - 1),
2397                ..TransactionOptions::default()
2398            },
2399            TransactionOptions {
2400                max_records: Some(usage.records - 1),
2401                ..TransactionOptions::default()
2402            },
2403        ] {
2404            let mut transaction = graph.transaction_with_options(options).unwrap();
2405            assert!(matches!(
2406                transaction.query("CREATE (:BudgetBoundary {value: 1})", Params::new()),
2407                Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2408            ));
2409            transaction.rollback().unwrap();
2410        }
2411
2412        let savepoint_limit = usage.checked_add(savepoint_usage).unwrap();
2413        let mut transaction = graph
2414            .transaction_with_options(TransactionOptions {
2415                max_workspace_bytes: Some(savepoint_limit.bytes),
2416                max_records: Some(savepoint_limit.records),
2417                ..TransactionOptions::default()
2418            })
2419            .unwrap();
2420        transaction
2421            .query("CREATE (:BudgetBoundary {value: 1})", Params::new())
2422            .unwrap();
2423        let _ = transaction.savepoint().unwrap();
2424        assert!(matches!(
2425            transaction.savepoint(),
2426            Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2427        ));
2428        transaction.rollback().unwrap();
2429    }
2430
2431    #[test]
2432    fn retained_savepoints_reduce_per_mutation_workspace_limit() {
2433        let home = tempfile::tempdir().unwrap();
2434        let database = home.path().join("data/databases/neo4j");
2435        Neo4jStorage::initialize_if_empty(&database).unwrap();
2436        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2437
2438        let (one_node_usage, savepoint_usage) = {
2439            let transaction = graph.transaction().unwrap();
2440            let savepoint_usage = transaction.savepoint_usage().unwrap();
2441            transaction
2442                .graph
2443                .write_storage()
2444                .unwrap()
2445                .create_node(Vec::new(), Properties::new())
2446                .unwrap();
2447            let one_node_usage = transaction.graph.backend.workspace_usage().unwrap();
2448            transaction.rollback().unwrap();
2449            (one_node_usage, savepoint_usage)
2450        };
2451        let limit = one_node_usage.checked_add(savepoint_usage).unwrap();
2452
2453        let mut transaction = graph
2454            .transaction_with_options(TransactionOptions {
2455                max_workspace_bytes: Some(limit.bytes),
2456                ..TransactionOptions::default()
2457            })
2458            .unwrap();
2459        let _ = transaction.savepoint().unwrap();
2460        transaction
2461            .graph
2462            .write_storage()
2463            .unwrap()
2464            .create_node(Vec::new(), Properties::new())
2465            .unwrap();
2466        assert!(matches!(
2467            transaction
2468                .graph
2469                .write_storage()
2470                .unwrap()
2471                .create_node(Vec::new(), Properties::new()),
2472            Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2473        ));
2474        transaction.rollback().unwrap();
2475    }
2476
2477    #[test]
2478    fn savepoint_rollback_does_not_clear_deadline_or_cancellation() {
2479        let home = tempfile::tempdir().unwrap();
2480        let database = home.path().join("data/databases/neo4j");
2481        Neo4jStorage::initialize_if_empty(&database).unwrap();
2482        let mut graph = Graph::open_neo4j_writable(&database).unwrap();
2483
2484        {
2485            let mut transaction = graph.transaction().unwrap();
2486            let savepoint = transaction.savepoint().unwrap();
2487            transaction.deadline = Some(Instant::now());
2488            assert!(matches!(
2489                transaction.query("MATCH (n) RETURN n", Params::new()),
2490                Err(Error::Transaction(TransactionErrorKind::TimedOut))
2491            ));
2492            transaction.rollback_to(savepoint).unwrap();
2493            assert!(matches!(
2494                transaction.query("MATCH (n) RETURN n", Params::new()),
2495                Err(Error::Transaction(TransactionErrorKind::TimedOut))
2496            ));
2497            transaction.rollback().unwrap();
2498        }
2499
2500        {
2501            let token = CancellationToken::new();
2502            let mut transaction = graph
2503                .transaction_with_options(TransactionOptions {
2504                    cancellation_token: Some(token.clone()),
2505                    ..TransactionOptions::default()
2506                })
2507                .unwrap();
2508            let savepoint = transaction.savepoint().unwrap();
2509            token.cancel();
2510            assert!(matches!(
2511                transaction.query("MATCH (n) RETURN n", Params::new()),
2512                Err(Error::Transaction(TransactionErrorKind::Cancelled))
2513            ));
2514            transaction.rollback_to(savepoint).unwrap();
2515            assert!(matches!(
2516                transaction.query("MATCH (n) RETURN n", Params::new()),
2517                Err(Error::Transaction(TransactionErrorKind::Cancelled))
2518            ));
2519            transaction.rollback().unwrap();
2520        }
2521    }
2522
2523    #[test]
2524    fn read_only_savepoints_charge_their_handle_state() {
2525        let home = tempfile::tempdir().unwrap();
2526        let database = home.path().join("data/databases/neo4j");
2527        Neo4jStorage::initialize_if_empty(&database).unwrap();
2528        let mut graph = Graph::open_neo4j(&database).unwrap();
2529        let savepoint_bytes = std::mem::size_of::<TransactionSavepoint>();
2530
2531        {
2532            let mut transaction = graph
2533                .transaction_with_options(TransactionOptions {
2534                    max_workspace_bytes: Some(savepoint_bytes),
2535                    ..TransactionOptions::default()
2536                })
2537                .unwrap();
2538            let _ = transaction.savepoint().unwrap();
2539            assert!(matches!(
2540                transaction.savepoint(),
2541                Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2542            ));
2543            transaction.rollback().unwrap();
2544        }
2545
2546        let mut transaction = graph
2547            .transaction_with_options(TransactionOptions {
2548                max_workspace_bytes: Some(savepoint_bytes - 1),
2549                ..TransactionOptions::default()
2550            })
2551            .unwrap();
2552        assert!(matches!(
2553            transaction.savepoint(),
2554            Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2555        ));
2556        transaction.rollback().unwrap();
2557    }
2558
2559    #[test]
2560    fn procedure_materialization_obeys_the_query_memory_limit() {
2561        let home = tempfile::tempdir().unwrap();
2562        let database = home.path().join("data/databases/neo4j");
2563        Neo4jStorage::initialize_if_empty(&database).unwrap();
2564        let mut graph = Graph::open_neo4j(&database).unwrap();
2565
2566        assert_eq!(
2567            graph
2568                .query("CALL db.schema.visualization()", Params::new())
2569                .unwrap()
2570                .rows
2571                .len(),
2572            1
2573        );
2574
2575        let mut transaction = graph
2576            .transaction_with_options(TransactionOptions {
2577                max_query_memory_bytes: Some(0),
2578                ..TransactionOptions::default()
2579            })
2580            .unwrap();
2581        assert!(matches!(
2582            transaction.query("CALL db.schema.visualization()", Params::new()),
2583            Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2584        ));
2585        assert!(matches!(
2586            transaction.query("CALL db.ping()", Params::new()),
2587            Err(Error::Transaction(TransactionErrorKind::ResourceLimit))
2588        ));
2589        transaction.rollback().unwrap();
2590    }
2591
2592    #[test]
2593    fn controlled_executor_propagates_deadlines_and_clears_control_state() {
2594        let home = tempfile::tempdir().unwrap();
2595        let database = home.path().join("data/databases/neo4j");
2596        Neo4jStorage::initialize_if_empty(&database).unwrap();
2597        let mut graph = Graph::open_neo4j(&database).unwrap();
2598        let statement = parse_statement("MATCH (n) RETURN n").unwrap();
2599
2600        assert!(matches!(
2601            graph.execute_controlled_statement(
2602                statement,
2603                &Params::new(),
2604                QueryControl {
2605                    deadline: Some(Instant::now()),
2606                    cancellation_token: None,
2607                    max_query_memory_bytes: None,
2608                    query_memory_bytes: Cell::new(0),
2609                },
2610            ),
2611            Err(Error::Transaction(TransactionErrorKind::TimedOut))
2612        ));
2613        assert!(graph.query_control.is_none());
2614        assert!(graph
2615            .query("MATCH (n) RETURN n", Params::new())
2616            .unwrap()
2617            .rows
2618            .is_empty());
2619    }
2620
2621    #[test]
2622    fn controlled_write_range_observes_deadline() {
2623        let home = tempfile::tempdir().unwrap();
2624        let database = home.path().join("data/databases/neo4j");
2625        Neo4jStorage::initialize_if_empty(&database).unwrap();
2626        let graph = Graph::open_neo4j(&database).unwrap();
2627        let control = QueryControl {
2628            deadline: Some(Instant::now()),
2629            cancellation_token: None,
2630            max_query_memory_bytes: None,
2631            query_memory_bytes: Cell::new(0),
2632        };
2633        let storage = ControlledStorage {
2634            storage: graph.backend.read(),
2635            control: Some(&control),
2636        };
2637
2638        assert!(matches!(
2639            evaluate_write_range_value(
2640                Value::Integer(1),
2641                Value::Integer(1_000_000),
2642                None,
2643                Some(&storage),
2644            ),
2645            Err(Error::Transaction(TransactionErrorKind::TimedOut))
2646        ));
2647    }
2648}
2649
2650fn find_merge_node(
2651    storage: &dyn StorageInterface,
2652    pattern: &NodePattern,
2653    properties: &Properties,
2654) -> Result<Option<NodeId>> {
2655    for node_id in storage.node_ids() {
2656        storage.check_query_control()?;
2657        let node = storage
2658            .node(node_id)
2659            .ok_or_else(|| Error::Execution(format!("missing node id {node_id}")))?;
2660        let mut labels_match = true;
2661        for label in &pattern.labels {
2662            if controlled_position(storage, &node.labels, |node_label| node_label == label)?
2663                .is_none()
2664            {
2665                labels_match = false;
2666                break;
2667            }
2668        }
2669        if labels_match
2670            && properties
2671                .iter()
2672                .all(|(key, value)| node.properties.get(key) == Some(value))
2673        {
2674            return Ok(Some(node_id));
2675        }
2676    }
2677
2678    Ok(None)
2679}
2680
2681fn find_merge_relationship(
2682    storage: &dyn StorageInterface,
2683    start: NodeId,
2684    end: NodeId,
2685    direction: Direction,
2686    relationship_types: &[String],
2687    properties: &Properties,
2688) -> Result<Option<RelationshipId>> {
2689    for relationship_id in storage.outgoing_relationships(start) {
2690        storage.check_query_control()?;
2691        let relationship = storage.relationship(*relationship_id).ok_or_else(|| {
2692            Error::Execution(format!("missing relationship id {relationship_id}"))
2693        })?;
2694        if relationship.end == end
2695            && relationship_matches_merge_properties(
2696                storage,
2697                relationship,
2698                relationship_types,
2699                properties,
2700            )?
2701        {
2702            return Ok(Some(*relationship_id));
2703        }
2704    }
2705
2706    if direction == Direction::Undirected {
2707        for relationship_id in storage.incoming_relationships(start) {
2708            storage.check_query_control()?;
2709            let relationship = storage.relationship(*relationship_id).ok_or_else(|| {
2710                Error::Execution(format!("missing relationship id {relationship_id}"))
2711            })?;
2712            if relationship.start == end
2713                && relationship_matches_merge_properties(
2714                    storage,
2715                    relationship,
2716                    relationship_types,
2717                    properties,
2718                )?
2719            {
2720                return Ok(Some(*relationship_id));
2721            }
2722        }
2723    }
2724
2725    Ok(None)
2726}
2727
2728fn set_item_variable(item: &SetItem) -> String {
2729    match item {
2730        SetItem::Property { variable, .. }
2731        | SetItem::PropertiesMerge { variable, .. }
2732        | SetItem::PropertiesReplace { variable, .. }
2733        | SetItem::Label { variable, .. } => variable.clone(),
2734    }
2735}
2736
2737fn collect_expression_variables(expression: &Expression) -> BTreeSet<String> {
2738    let mut variables = BTreeSet::new();
2739    collect_expression_variables_inner(expression, &mut variables);
2740    variables
2741}
2742
2743fn collect_set_item_variables(item: &SetItem) -> BTreeSet<String> {
2744    match item {
2745        SetItem::Property { expression, .. }
2746        | SetItem::PropertiesMerge { expression, .. }
2747        | SetItem::PropertiesReplace { expression, .. } => collect_expression_variables(expression),
2748        SetItem::Label { .. } => BTreeSet::new(),
2749    }
2750}
2751
2752fn collect_expression_variables_inner(expression: &Expression, variables: &mut BTreeSet<String>) {
2753    match expression {
2754        Expression::Literal(_) | Expression::Parameter(_) | Expression::Pi | Expression::E => {}
2755        Expression::Operand(operand) => collect_operand_variables(operand, variables),
2756        Expression::Add(left, right)
2757        | Expression::Subtract(left, right)
2758        | Expression::Multiply(left, right)
2759        | Expression::Divide(left, right)
2760        | Expression::Modulo(left, right) => {
2761            collect_expression_variables_inner(left, variables);
2762            collect_expression_variables_inner(right, variables);
2763        }
2764        Expression::List(items) | Expression::Coalesce(items) => {
2765            for item in items {
2766                collect_expression_variables_inner(item, variables);
2767            }
2768        }
2769        Expression::Map(entries) => {
2770            for value in entries.values() {
2771                collect_expression_variables_inner(value, variables);
2772            }
2773        }
2774        Expression::MapProjection {
2775            variable: projection_variable,
2776            items,
2777        } => {
2778            variables.insert(projection_variable.clone());
2779            for item in items {
2780                if let crate::cypher::ast::MapProjectionItem::Expression { expression, .. } = item {
2781                    collect_expression_variables_inner(expression, variables);
2782                }
2783            }
2784        }
2785        Expression::ToLower(expression)
2786        | Expression::ToUpper(expression)
2787        | Expression::ToString(expression)
2788        | Expression::ToInteger(expression)
2789        | Expression::ToFloat(expression)
2790        | Expression::ToBoolean(expression)
2791        | Expression::ToStringOrNull(expression)
2792        | Expression::ToIntegerOrNull(expression)
2793        | Expression::ToFloatOrNull(expression)
2794        | Expression::ToBooleanOrNull(expression)
2795        | Expression::IsEmpty(expression)
2796        | Expression::Head(expression)
2797        | Expression::Last(expression)
2798        | Expression::Tail(expression)
2799        | Expression::Size(expression)
2800        | Expression::Reverse(expression)
2801        | Expression::Abs(expression)
2802        | Expression::Sign(expression)
2803        | Expression::Sqrt(expression)
2804        | Expression::Round(expression)
2805        | Expression::Log(expression)
2806        | Expression::Log10(expression)
2807        | Expression::Exp(expression)
2808        | Expression::Haversin(expression) => {
2809            collect_expression_variables_inner(expression, variables)
2810        }
2811        Expression::Range { start, end, step } => {
2812            collect_expression_variables_inner(start, variables);
2813            collect_expression_variables_inner(end, variables);
2814            if let Some(step) = step {
2815                collect_expression_variables_inner(step, variables);
2816            }
2817        }
2818        Expression::ListIndex { value, index } => {
2819            collect_expression_variables_inner(value, variables);
2820            collect_expression_variables_inner(index, variables);
2821        }
2822        Expression::ListSlice { value, start, end } => {
2823            collect_expression_variables_inner(value, variables);
2824            if let Some(start) = start {
2825                collect_expression_variables_inner(start, variables);
2826            }
2827            if let Some(end) = end {
2828                collect_expression_variables_inner(end, variables);
2829            }
2830        }
2831        Expression::Substring {
2832            value,
2833            start,
2834            length,
2835        } => {
2836            collect_expression_variables_inner(value, variables);
2837            collect_expression_variables_inner(start, variables);
2838            if let Some(length) = length {
2839                collect_expression_variables_inner(length, variables);
2840            }
2841        }
2842        Expression::Replace {
2843            value,
2844            search,
2845            replacement,
2846        } => {
2847            collect_expression_variables_inner(value, variables);
2848            collect_expression_variables_inner(search, variables);
2849            collect_expression_variables_inner(replacement, variables);
2850        }
2851        Expression::Trim { expression, .. }
2852        | Expression::StringSlice {
2853            value: expression, ..
2854        }
2855        | Expression::Rounding { expression, .. }
2856        | Expression::AngleConversion { expression, .. }
2857        | Expression::Trigonometric { expression, .. }
2858        | Expression::InverseTrigonometric { expression, .. } => {
2859            collect_expression_variables_inner(expression, variables)
2860        }
2861        Expression::Split { value, delimiter } => {
2862            collect_expression_variables_inner(value, variables);
2863            collect_expression_variables_inner(delimiter, variables);
2864        }
2865        Expression::Atan2 { y, x } => {
2866            collect_expression_variables_inner(y, variables);
2867            collect_expression_variables_inner(x, variables);
2868        }
2869        Expression::ListPredicate {
2870            variable,
2871            list,
2872            predicate,
2873            ..
2874        } => {
2875            collect_expression_variables_inner(list, variables);
2876            let mut nested = BTreeSet::new();
2877            collect_predicate_variables(predicate, &mut nested);
2878            nested.remove(variable);
2879            variables.extend(nested);
2880        }
2881        Expression::ListComprehension {
2882            variable,
2883            list,
2884            predicate,
2885            projection,
2886        } => {
2887            collect_expression_variables_inner(list, variables);
2888            let mut nested = BTreeSet::new();
2889            if let Some(predicate) = predicate {
2890                collect_predicate_variables(predicate, &mut nested);
2891            }
2892            collect_expression_variables_inner(projection, &mut nested);
2893            nested.remove(variable);
2894            variables.extend(nested);
2895        }
2896        Expression::PatternComprehension {
2897            pattern,
2898            predicate,
2899            projection,
2900        } => {
2901            let mut pattern_variables = Vec::new();
2902            collect_pattern_entity_variables(pattern, &mut pattern_variables);
2903            variables.extend(pattern_variables);
2904            if let Some(predicate) = predicate {
2905                collect_predicate_variables(predicate, variables);
2906            }
2907            collect_expression_variables_inner(projection, variables);
2908        }
2909        Expression::Reduce {
2910            accumulator,
2911            initial,
2912            variable,
2913            list,
2914            expression,
2915        } => {
2916            collect_expression_variables_inner(initial, variables);
2917            collect_expression_variables_inner(list, variables);
2918            let mut nested = BTreeSet::new();
2919            collect_expression_variables_inner(expression, &mut nested);
2920            nested.remove(accumulator);
2921            nested.remove(variable);
2922            variables.extend(nested);
2923        }
2924        Expression::Case {
2925            alternatives,
2926            else_expression,
2927        } => {
2928            for alternative in alternatives {
2929                collect_predicate_variables(&alternative.predicate, variables);
2930                collect_expression_variables_inner(&alternative.expression, variables);
2931            }
2932            collect_expression_variables_inner(else_expression, variables);
2933        }
2934        Expression::SimpleCase {
2935            operand,
2936            alternatives,
2937            else_expression,
2938        } => {
2939            collect_expression_variables_inner(operand, variables);
2940            for alternative in alternatives {
2941                collect_expression_variables_inner(&alternative.value, variables);
2942                collect_expression_variables_inner(&alternative.expression, variables);
2943            }
2944            collect_expression_variables_inner(else_expression, variables);
2945        }
2946        Expression::Predicate(predicate) => collect_predicate_variables(predicate, variables),
2947    }
2948}
2949
2950fn collect_predicate_variables(predicate: &Predicate, variables: &mut BTreeSet<String>) {
2951    match predicate {
2952        Predicate::Comparison { left, right, .. } => {
2953            collect_expression_variables_inner(left, variables);
2954            collect_expression_variables_inner(right, variables);
2955        }
2956        Predicate::StringMatch { left, right, .. } => {
2957            collect_expression_variables_inner(left, variables);
2958            collect_expression_variables_inner(right, variables);
2959        }
2960        Predicate::In { item, list } => {
2961            collect_expression_variables_inner(item, variables);
2962            collect_expression_variables_inner(list, variables);
2963        }
2964        Predicate::And(left, right) | Predicate::Or(left, right) | Predicate::Xor(left, right) => {
2965            collect_predicate_variables(left, variables);
2966            collect_predicate_variables(right, variables);
2967        }
2968        Predicate::Not(inner) => collect_predicate_variables(inner, variables),
2969        Predicate::Pattern(pattern) => {
2970            if let Some(variable) = &pattern.start.variable {
2971                variables.insert(variable.clone());
2972            }
2973            for chain in &pattern.chains {
2974                if let Some(variable) = &chain.node.variable {
2975                    variables.insert(variable.clone());
2976                }
2977            }
2978        }
2979        Predicate::IsNull(expression) | Predicate::IsNotNull(expression) => {
2980            collect_expression_variables_inner(expression, variables)
2981        }
2982        Predicate::Boolean(expression) => collect_expression_variables_inner(expression, variables),
2983        Predicate::Exists(operand) => collect_operand_variables(operand, variables),
2984        Predicate::ExistsSubquery(matches) => {
2985            for clause in matches {
2986                for pattern in &clause.patterns {
2987                    collect_pattern_variables(pattern, variables);
2988                }
2989                if let Some(predicate) = &clause.predicate {
2990                    collect_predicate_variables(predicate, variables);
2991                }
2992            }
2993        }
2994    }
2995}
2996
2997fn collect_pattern_variables(
2998    pattern: &crate::cypher::ast::Pattern,
2999    variables: &mut BTreeSet<String>,
3000) {
3001    if let Some(variable) = &pattern.start.variable {
3002        variables.insert(variable.clone());
3003    }
3004    for chain in &pattern.chains {
3005        if let Some(variable) = &chain.relationship.variable {
3006            variables.insert(variable.clone());
3007        }
3008        if let Some(variable) = &chain.node.variable {
3009            variables.insert(variable.clone());
3010        }
3011    }
3012}
3013
3014fn collect_operand_variables(operand: &Operand, variables: &mut BTreeSet<String>) {
3015    match operand {
3016        Operand::Variable(variable) => {
3017            variables.insert(variable.clone());
3018        }
3019        Operand::Property { variable, .. } => {
3020            variables.insert(variable.clone());
3021        }
3022        Operand::DynamicProperty { variable, key } => {
3023            variables.insert(variable.clone());
3024            collect_expression_variables_inner(key, variables);
3025        }
3026        Operand::Literal(_) | Operand::Parameter(_) => {}
3027    }
3028}
3029
3030fn substitute_set_item_value(item: &SetItem, variable: &str, value: &Value) -> SetItem {
3031    match item {
3032        SetItem::Property {
3033            variable: item_variable,
3034            key,
3035            expression,
3036        } => SetItem::Property {
3037            variable: item_variable.clone(),
3038            key: key.clone(),
3039            expression: substitute_expression_value(expression, variable, value),
3040        },
3041        SetItem::PropertiesMerge {
3042            variable: item_variable,
3043            expression,
3044        } => SetItem::PropertiesMerge {
3045            variable: item_variable.clone(),
3046            expression: substitute_expression_value(expression, variable, value),
3047        },
3048        SetItem::PropertiesReplace {
3049            variable: item_variable,
3050            expression,
3051        } => SetItem::PropertiesReplace {
3052            variable: item_variable.clone(),
3053            expression: substitute_expression_value(expression, variable, value),
3054        },
3055        SetItem::Label {
3056            variable: item_variable,
3057            labels,
3058        } => SetItem::Label {
3059            variable: item_variable.clone(),
3060            labels: labels.clone(),
3061        },
3062    }
3063}
3064
3065fn substitute_expression_value(
3066    expression: &Expression,
3067    variable: &str,
3068    value: &Value,
3069) -> Expression {
3070    match expression {
3071        Expression::Literal(_) | Expression::Parameter(_) | Expression::Pi | Expression::E => {
3072            expression.clone()
3073        }
3074        Expression::Operand(operand) => {
3075            Expression::Operand(substitute_operand_value(operand, variable, value))
3076        }
3077        Expression::Add(left, right) => Expression::Add(
3078            Box::new(substitute_expression_value(left, variable, value)),
3079            Box::new(substitute_expression_value(right, variable, value)),
3080        ),
3081        Expression::Subtract(left, right) => Expression::Subtract(
3082            Box::new(substitute_expression_value(left, variable, value)),
3083            Box::new(substitute_expression_value(right, variable, value)),
3084        ),
3085        Expression::Multiply(left, right) => Expression::Multiply(
3086            Box::new(substitute_expression_value(left, variable, value)),
3087            Box::new(substitute_expression_value(right, variable, value)),
3088        ),
3089        Expression::Divide(left, right) => Expression::Divide(
3090            Box::new(substitute_expression_value(left, variable, value)),
3091            Box::new(substitute_expression_value(right, variable, value)),
3092        ),
3093        Expression::Modulo(left, right) => Expression::Modulo(
3094            Box::new(substitute_expression_value(left, variable, value)),
3095            Box::new(substitute_expression_value(right, variable, value)),
3096        ),
3097        Expression::List(items) => Expression::List(
3098            items
3099                .iter()
3100                .map(|item| substitute_expression_value(item, variable, value))
3101                .collect(),
3102        ),
3103        Expression::Map(entries) => Expression::Map(
3104            entries
3105                .iter()
3106                .map(|(key, expression)| {
3107                    (
3108                        key.clone(),
3109                        substitute_expression_value(expression, variable, value),
3110                    )
3111                })
3112                .collect(),
3113        ),
3114        Expression::MapProjection {
3115            variable: projection_variable,
3116            items,
3117        } => Expression::MapProjection {
3118            variable: projection_variable.clone(),
3119            items: items
3120                .iter()
3121                .map(|item| match item {
3122                    crate::cypher::ast::MapProjectionItem::AllProperties => {
3123                        crate::cypher::ast::MapProjectionItem::AllProperties
3124                    }
3125                    crate::cypher::ast::MapProjectionItem::Property(key) => {
3126                        crate::cypher::ast::MapProjectionItem::Property(key.clone())
3127                    }
3128                    crate::cypher::ast::MapProjectionItem::Variable(variable) => {
3129                        crate::cypher::ast::MapProjectionItem::Variable(variable.clone())
3130                    }
3131                    crate::cypher::ast::MapProjectionItem::Expression { key, expression } => {
3132                        crate::cypher::ast::MapProjectionItem::Expression {
3133                            key: key.clone(),
3134                            expression: substitute_expression_value(expression, variable, value),
3135                        }
3136                    }
3137                })
3138                .collect(),
3139        },
3140        Expression::Coalesce(items) => Expression::Coalesce(
3141            items
3142                .iter()
3143                .map(|item| substitute_expression_value(item, variable, value))
3144                .collect(),
3145        ),
3146        Expression::ToLower(expression) => Expression::ToLower(Box::new(
3147            substitute_expression_value(expression, variable, value),
3148        )),
3149        Expression::ToUpper(expression) => Expression::ToUpper(Box::new(
3150            substitute_expression_value(expression, variable, value),
3151        )),
3152        Expression::ToString(expression) => Expression::ToString(Box::new(
3153            substitute_expression_value(expression, variable, value),
3154        )),
3155        Expression::ToInteger(expression) => Expression::ToInteger(Box::new(
3156            substitute_expression_value(expression, variable, value),
3157        )),
3158        Expression::ToFloat(expression) => Expression::ToFloat(Box::new(
3159            substitute_expression_value(expression, variable, value),
3160        )),
3161        Expression::ToBoolean(expression) => Expression::ToBoolean(Box::new(
3162            substitute_expression_value(expression, variable, value),
3163        )),
3164        Expression::ToStringOrNull(expression) => Expression::ToStringOrNull(Box::new(
3165            substitute_expression_value(expression, variable, value),
3166        )),
3167        Expression::ToIntegerOrNull(expression) => Expression::ToIntegerOrNull(Box::new(
3168            substitute_expression_value(expression, variable, value),
3169        )),
3170        Expression::ToFloatOrNull(expression) => Expression::ToFloatOrNull(Box::new(
3171            substitute_expression_value(expression, variable, value),
3172        )),
3173        Expression::ToBooleanOrNull(expression) => Expression::ToBooleanOrNull(Box::new(
3174            substitute_expression_value(expression, variable, value),
3175        )),
3176        Expression::IsEmpty(expression) => Expression::IsEmpty(Box::new(
3177            substitute_expression_value(expression, variable, value),
3178        )),
3179        Expression::Head(expression) => Expression::Head(Box::new(substitute_expression_value(
3180            expression, variable, value,
3181        ))),
3182        Expression::Last(expression) => Expression::Last(Box::new(substitute_expression_value(
3183            expression, variable, value,
3184        ))),
3185        Expression::Tail(expression) => Expression::Tail(Box::new(substitute_expression_value(
3186            expression, variable, value,
3187        ))),
3188        Expression::Range { start, end, step } => Expression::Range {
3189            start: Box::new(substitute_expression_value(start, variable, value)),
3190            end: Box::new(substitute_expression_value(end, variable, value)),
3191            step: step
3192                .as_ref()
3193                .map(|step| Box::new(substitute_expression_value(step, variable, value))),
3194        },
3195        Expression::ListIndex {
3196            value: list_value,
3197            index,
3198        } => Expression::ListIndex {
3199            value: Box::new(substitute_expression_value(list_value, variable, value)),
3200            index: Box::new(substitute_expression_value(index, variable, value)),
3201        },
3202        Expression::ListSlice {
3203            value: list_value,
3204            start,
3205            end,
3206        } => Expression::ListSlice {
3207            value: Box::new(substitute_expression_value(list_value, variable, value)),
3208            start: start
3209                .as_ref()
3210                .map(|start| Box::new(substitute_expression_value(start, variable, value))),
3211            end: end
3212                .as_ref()
3213                .map(|end| Box::new(substitute_expression_value(end, variable, value))),
3214        },
3215        Expression::Size(expression) => Expression::Size(Box::new(substitute_expression_value(
3216            expression, variable, value,
3217        ))),
3218        Expression::Substring {
3219            value: inner,
3220            start,
3221            length,
3222        } => Expression::Substring {
3223            value: Box::new(substitute_expression_value(inner, variable, value)),
3224            start: Box::new(substitute_expression_value(start, variable, value)),
3225            length: length
3226                .as_ref()
3227                .map(|length| Box::new(substitute_expression_value(length, variable, value))),
3228        },
3229        Expression::Replace {
3230            value: inner,
3231            search,
3232            replacement,
3233        } => Expression::Replace {
3234            value: Box::new(substitute_expression_value(inner, variable, value)),
3235            search: Box::new(substitute_expression_value(search, variable, value)),
3236            replacement: Box::new(substitute_expression_value(replacement, variable, value)),
3237        },
3238        Expression::Trim { mode, expression } => Expression::Trim {
3239            mode: mode.clone(),
3240            expression: Box::new(substitute_expression_value(expression, variable, value)),
3241        },
3242        Expression::Split {
3243            value: inner,
3244            delimiter,
3245        } => Expression::Split {
3246            value: Box::new(substitute_expression_value(inner, variable, value)),
3247            delimiter: Box::new(substitute_expression_value(delimiter, variable, value)),
3248        },
3249        Expression::StringSlice {
3250            mode,
3251            value: inner,
3252            length,
3253        } => Expression::StringSlice {
3254            mode: mode.clone(),
3255            value: Box::new(substitute_expression_value(inner, variable, value)),
3256            length: Box::new(substitute_expression_value(length, variable, value)),
3257        },
3258        Expression::Reverse(expression) => Expression::Reverse(Box::new(
3259            substitute_expression_value(expression, variable, value),
3260        )),
3261        Expression::Abs(expression) => Expression::Abs(Box::new(substitute_expression_value(
3262            expression, variable, value,
3263        ))),
3264        Expression::Rounding { mode, expression } => Expression::Rounding {
3265            mode: mode.clone(),
3266            expression: Box::new(substitute_expression_value(expression, variable, value)),
3267        },
3268        Expression::Sign(expression) => Expression::Sign(Box::new(substitute_expression_value(
3269            expression, variable, value,
3270        ))),
3271        Expression::Sqrt(expression) => Expression::Sqrt(Box::new(substitute_expression_value(
3272            expression, variable, value,
3273        ))),
3274        Expression::Round(expression) => Expression::Round(Box::new(substitute_expression_value(
3275            expression, variable, value,
3276        ))),
3277        Expression::Log(expression) => Expression::Log(Box::new(substitute_expression_value(
3278            expression, variable, value,
3279        ))),
3280        Expression::Log10(expression) => Expression::Log10(Box::new(substitute_expression_value(
3281            expression, variable, value,
3282        ))),
3283        Expression::Exp(expression) => Expression::Exp(Box::new(substitute_expression_value(
3284            expression, variable, value,
3285        ))),
3286        Expression::AngleConversion { mode, expression } => Expression::AngleConversion {
3287            mode: mode.clone(),
3288            expression: Box::new(substitute_expression_value(expression, variable, value)),
3289        },
3290        Expression::Trigonometric { mode, expression } => Expression::Trigonometric {
3291            mode: mode.clone(),
3292            expression: Box::new(substitute_expression_value(expression, variable, value)),
3293        },
3294        Expression::InverseTrigonometric { mode, expression } => Expression::InverseTrigonometric {
3295            mode: mode.clone(),
3296            expression: Box::new(substitute_expression_value(expression, variable, value)),
3297        },
3298        Expression::Atan2 { y, x } => Expression::Atan2 {
3299            y: Box::new(substitute_expression_value(y, variable, value)),
3300            x: Box::new(substitute_expression_value(x, variable, value)),
3301        },
3302        Expression::Haversin(expression) => Expression::Haversin(Box::new(
3303            substitute_expression_value(expression, variable, value),
3304        )),
3305        Expression::ListPredicate {
3306            mode,
3307            variable: inner,
3308            list,
3309            predicate,
3310        } => {
3311            if inner == variable {
3312                expression.clone()
3313            } else {
3314                Expression::ListPredicate {
3315                    mode: *mode,
3316                    variable: inner.clone(),
3317                    list: Box::new(substitute_expression_value(list, variable, value)),
3318                    predicate: Box::new(substitute_predicate_value(predicate, variable, value)),
3319                }
3320            }
3321        }
3322        Expression::ListComprehension {
3323            variable: inner,
3324            list,
3325            predicate,
3326            projection,
3327        } => {
3328            if inner == variable {
3329                expression.clone()
3330            } else {
3331                Expression::ListComprehension {
3332                    variable: inner.clone(),
3333                    list: Box::new(substitute_expression_value(list, variable, value)),
3334                    predicate: predicate.as_ref().map(|predicate| {
3335                        Box::new(substitute_predicate_value(predicate, variable, value))
3336                    }),
3337                    projection: Box::new(substitute_expression_value(projection, variable, value)),
3338                }
3339            }
3340        }
3341        Expression::PatternComprehension {
3342            pattern,
3343            predicate,
3344            projection,
3345        } => Expression::PatternComprehension {
3346            pattern: pattern.clone(),
3347            predicate: predicate
3348                .as_ref()
3349                .map(|predicate| Box::new(substitute_predicate_value(predicate, variable, value))),
3350            projection: Box::new(substitute_expression_value(projection, variable, value)),
3351        },
3352        Expression::Reduce {
3353            accumulator,
3354            initial,
3355            variable: inner,
3356            list,
3357            expression: reduce_expression,
3358        } => {
3359            let initial = Box::new(substitute_expression_value(initial, variable, value));
3360            let list = Box::new(substitute_expression_value(list, variable, value));
3361            if accumulator == variable || inner == variable {
3362                Expression::Reduce {
3363                    accumulator: accumulator.clone(),
3364                    initial,
3365                    variable: inner.clone(),
3366                    list,
3367                    expression: reduce_expression.clone(),
3368                }
3369            } else {
3370                Expression::Reduce {
3371                    accumulator: accumulator.clone(),
3372                    initial,
3373                    variable: inner.clone(),
3374                    list,
3375                    expression: Box::new(substitute_expression_value(
3376                        reduce_expression,
3377                        variable,
3378                        value,
3379                    )),
3380                }
3381            }
3382        }
3383        Expression::Case {
3384            alternatives,
3385            else_expression,
3386        } => Expression::Case {
3387            alternatives: alternatives
3388                .iter()
3389                .map(|alternative| crate::cypher::ast::CaseAlternative {
3390                    predicate: substitute_predicate_value(&alternative.predicate, variable, value),
3391                    expression: substitute_expression_value(
3392                        &alternative.expression,
3393                        variable,
3394                        value,
3395                    ),
3396                })
3397                .collect(),
3398            else_expression: Box::new(substitute_expression_value(
3399                else_expression,
3400                variable,
3401                value,
3402            )),
3403        },
3404        Expression::SimpleCase {
3405            operand,
3406            alternatives,
3407            else_expression,
3408        } => Expression::SimpleCase {
3409            operand: Box::new(substitute_expression_value(operand, variable, value)),
3410            alternatives: alternatives
3411                .iter()
3412                .map(|alternative| crate::cypher::ast::SimpleCaseAlternative {
3413                    value: substitute_expression_value(&alternative.value, variable, value),
3414                    expression: substitute_expression_value(
3415                        &alternative.expression,
3416                        variable,
3417                        value,
3418                    ),
3419                })
3420                .collect(),
3421            else_expression: Box::new(substitute_expression_value(
3422                else_expression,
3423                variable,
3424                value,
3425            )),
3426        },
3427        Expression::Predicate(predicate) => Expression::Predicate(Box::new(
3428            substitute_predicate_value(predicate, variable, value),
3429        )),
3430    }
3431}
3432
3433fn substitute_predicate_value(predicate: &Predicate, variable: &str, value: &Value) -> Predicate {
3434    match predicate {
3435        Predicate::Comparison {
3436            left,
3437            operator,
3438            right,
3439        } => Predicate::Comparison {
3440            left: substitute_expression_value(left, variable, value),
3441            operator: *operator,
3442            right: substitute_expression_value(right, variable, value),
3443        },
3444        Predicate::In { item, list } => Predicate::In {
3445            item: substitute_expression_value(item, variable, value),
3446            list: substitute_expression_value(list, variable, value),
3447        },
3448        Predicate::StringMatch {
3449            left,
3450            operator,
3451            right,
3452        } => Predicate::StringMatch {
3453            left: substitute_expression_value(left, variable, value),
3454            operator: *operator,
3455            right: substitute_expression_value(right, variable, value),
3456        },
3457        Predicate::And(left, right) => Predicate::And(
3458            Box::new(substitute_predicate_value(left, variable, value)),
3459            Box::new(substitute_predicate_value(right, variable, value)),
3460        ),
3461        Predicate::Or(left, right) => Predicate::Or(
3462            Box::new(substitute_predicate_value(left, variable, value)),
3463            Box::new(substitute_predicate_value(right, variable, value)),
3464        ),
3465        Predicate::Xor(left, right) => Predicate::Xor(
3466            Box::new(substitute_predicate_value(left, variable, value)),
3467            Box::new(substitute_predicate_value(right, variable, value)),
3468        ),
3469        Predicate::Not(inner) => {
3470            Predicate::Not(Box::new(substitute_predicate_value(inner, variable, value)))
3471        }
3472        Predicate::Pattern(pattern) => Predicate::Pattern(pattern.clone()),
3473        Predicate::IsNull(expression) => {
3474            Predicate::IsNull(substitute_expression_value(expression, variable, value))
3475        }
3476        Predicate::IsNotNull(expression) => {
3477            Predicate::IsNotNull(substitute_expression_value(expression, variable, value))
3478        }
3479        Predicate::Exists(operand) => {
3480            Predicate::Exists(substitute_operand_value(operand, variable, value))
3481        }
3482        Predicate::ExistsSubquery(matches) => Predicate::ExistsSubquery(matches.clone()),
3483        Predicate::Boolean(expression) => {
3484            Predicate::Boolean(substitute_expression_value(expression, variable, value))
3485        }
3486    }
3487}
3488
3489fn substitute_operand_value(operand: &Operand, variable: &str, value: &Value) -> Operand {
3490    match operand {
3491        Operand::Variable(name) if name == variable => Operand::Literal(value.clone()),
3492        Operand::Literal(_) | Operand::Parameter(_) | Operand::Variable(_) => operand.clone(),
3493        Operand::Property {
3494            variable: item_variable,
3495            key,
3496        } => Operand::Property {
3497            variable: item_variable.clone(),
3498            key: key.clone(),
3499        },
3500        Operand::DynamicProperty {
3501            variable: item_variable,
3502            key,
3503        } => Operand::DynamicProperty {
3504            variable: item_variable.clone(),
3505            key: Box::new(substitute_expression_value(key, variable, value)),
3506        },
3507    }
3508}
3509
3510fn remove_item_variable(item: &RemoveItem) -> String {
3511    match item {
3512        RemoveItem::Property { variable, .. } | RemoveItem::Label { variable, .. } => {
3513            variable.clone()
3514        }
3515    }
3516}
3517
3518fn matched_relationship_variables(matches: &[MatchClause]) -> BTreeSet<String> {
3519    matches
3520        .iter()
3521        .flat_map(|clause| &clause.patterns)
3522        .flat_map(|pattern| &pattern.chains)
3523        .filter_map(|chain| chain.relationship.variable.clone())
3524        .collect()
3525}
3526
3527fn apply_set_item(
3528    storage: &mut dyn WritableStorage,
3529    ids: &BTreeMap<String, EntityId>,
3530    entity_id: EntityId,
3531    item: &SetItem,
3532    params: &Params,
3533) -> Result<()> {
3534    match item {
3535        SetItem::Property {
3536            key, expression, ..
3537        } => {
3538            let value = evaluate_write_expression_with_entities(storage, ids, expression, params)?;
3539            match (entity_id, value) {
3540                (EntityId::Node(node_id), Value::Null) => {
3541                    storage.remove_node_property(node_id, key)?;
3542                }
3543                (EntityId::Node(node_id), value) => {
3544                    storage.set_node_property(node_id, key.clone(), value)?;
3545                }
3546                (EntityId::Relationship(relationship_id), Value::Null) => {
3547                    storage.remove_relationship_property(relationship_id, key)?;
3548                }
3549                (EntityId::Relationship(relationship_id), value) => {
3550                    storage.set_relationship_property(relationship_id, key.clone(), value)?;
3551                }
3552            }
3553            Ok(())
3554        }
3555        SetItem::PropertiesReplace { expression, .. } => {
3556            let properties = evaluate_write_map_expression_with_entities(
3557                storage, ids, expression, params, "SET =", true,
3558            )?;
3559            match entity_id {
3560                EntityId::Node(node_id) => storage.replace_node_properties(node_id, properties),
3561                EntityId::Relationship(relationship_id) => {
3562                    storage.replace_relationship_properties(relationship_id, properties)
3563                }
3564            }
3565        }
3566        SetItem::PropertiesMerge { expression, .. } => {
3567            let properties = evaluate_write_map_expression_with_entities(
3568                storage, ids, expression, params, "SET +=", false,
3569            )?;
3570            for (key, value) in properties {
3571                match (entity_id, value) {
3572                    (EntityId::Node(node_id), Value::Null) => {
3573                        storage.remove_node_property(node_id, &key)?;
3574                    }
3575                    (EntityId::Node(node_id), value) => {
3576                        storage.set_node_property(node_id, key, value)?;
3577                    }
3578                    (EntityId::Relationship(relationship_id), Value::Null) => {
3579                        storage.remove_relationship_property(relationship_id, &key)?;
3580                    }
3581                    (EntityId::Relationship(relationship_id), value) => {
3582                        storage.set_relationship_property(relationship_id, key, value)?;
3583                    }
3584                }
3585            }
3586            Ok(())
3587        }
3588        SetItem::Label { labels, .. } => {
3589            let EntityId::Node(node_id) = entity_id else {
3590                return Err(Error::Validation(
3591                    "SET label item requires a node binding".to_string(),
3592                ));
3593            };
3594            for label in labels {
3595                storage.set_node_label(node_id, label.clone())?;
3596            }
3597            Ok(())
3598        }
3599    }
3600}
3601
3602fn evaluate_write_map_expression_with_entities(
3603    storage: &dyn StorageInterface,
3604    ids: &BTreeMap<String, EntityId>,
3605    expression: &Expression,
3606    params: &Params,
3607    operator: &str,
3608    drop_null_values: bool,
3609) -> Result<Properties> {
3610    let value = evaluate_write_expression_with_entities(storage, ids, expression, params)?;
3611    let Value::Map(properties) = value else {
3612        return Err(Error::Validation(format!(
3613            "{operator} requires a map expression"
3614        )));
3615    };
3616    if drop_null_values {
3617        Ok(properties
3618            .into_iter()
3619            .filter(|(_, value)| !matches!(value, Value::Null))
3620            .collect())
3621    } else {
3622        Ok(properties)
3623    }
3624}
3625
3626fn apply_remove_item(
3627    storage: &mut dyn WritableStorage,
3628    entity_id: EntityId,
3629    item: &RemoveItem,
3630) -> Result<()> {
3631    match item {
3632        RemoveItem::Property { key, .. } => match entity_id {
3633            EntityId::Node(node_id) => storage.remove_node_property(node_id, key),
3634            EntityId::Relationship(relationship_id) => {
3635                storage.remove_relationship_property(relationship_id, key)
3636            }
3637        },
3638        RemoveItem::Label { labels, .. } => {
3639            let EntityId::Node(node_id) = entity_id else {
3640                return Err(Error::Validation(
3641                    "REMOVE label item requires a node binding".to_string(),
3642                ));
3643            };
3644            for label in labels {
3645                storage.remove_node_label(node_id, label)?;
3646            }
3647            Ok(())
3648        }
3649    }
3650}
3651
3652fn relationship_write_endpoints(
3653    start: NodeId,
3654    end: NodeId,
3655    direction: Direction,
3656) -> (NodeId, NodeId) {
3657    match direction {
3658        Direction::Outgoing | Direction::Undirected => (start, end),
3659        Direction::Incoming => (end, start),
3660    }
3661}
3662
3663fn relationship_matches_merge_properties(
3664    storage: &dyn StorageInterface,
3665    relationship: &crate::graph_model::Relationship,
3666    relationship_types: &[String],
3667    properties: &Properties,
3668) -> Result<bool> {
3669    Ok(
3670        controlled_position(storage, relationship_types, |relationship_type| {
3671            relationship_type == &relationship.r#type
3672        })?
3673        .is_some()
3674            && properties
3675                .iter()
3676                .all(|(key, value)| relationship.properties.get(key) == Some(value)),
3677    )
3678}
3679
3680fn apply_merge_actions(
3681    storage: &mut dyn WritableStorage,
3682    entity_id: EntityId,
3683    variable: &str,
3684    created: bool,
3685    actions: &[MergeAction],
3686    params: &Params,
3687) -> Result<()> {
3688    let selected_branch = if created {
3689        MergeBranch::OnCreate
3690    } else {
3691        MergeBranch::OnMatch
3692    };
3693
3694    for action in actions
3695        .iter()
3696        .filter(|action| action.branch == selected_branch)
3697    {
3698        for item in &action.items {
3699            let item_variable = set_item_variable(item);
3700            if item_variable != variable {
3701                return Err(Error::Validation(format!(
3702                    "MERGE action SET target `{}` must match MERGE variable `{variable}`",
3703                    item_variable
3704                )));
3705            }
3706            let ids = BTreeMap::from([(variable.to_string(), entity_id)]);
3707            apply_set_item(storage, &ids, entity_id, item, params)?;
3708        }
3709    }
3710
3711    Ok(())
3712}
3713
3714struct RelationshipCreatePattern {
3715    start_variable: String,
3716    end_variable: String,
3717    relationship: RelationshipPattern,
3718}
3719
3720fn relationship_create_pattern(pattern: &Pattern) -> Result<RelationshipCreatePattern> {
3721    if pattern.variable.is_some() || pattern.shortest_path.is_some() || pattern.chains.len() != 1 {
3722        return Err(Error::UnsupportedQueryFeature(
3723            "CREATE relationship currently supports a single relationship pattern".to_string(),
3724        ));
3725    }
3726
3727    let start_variable = pattern.start.variable.clone().ok_or_else(|| {
3728        Error::Validation("CREATE relationship start node must use a variable".to_string())
3729    })?;
3730    let chain = pattern
3731        .chains
3732        .first()
3733        .ok_or_else(|| Error::Parse("CREATE relationship is missing relationship".to_string()))?;
3734    let end_variable = chain.node.variable.clone().ok_or_else(|| {
3735        Error::Validation("CREATE relationship end node must use a variable".to_string())
3736    })?;
3737
3738    if chain.relationship.variable_length {
3739        return Err(Error::UnsupportedQueryFeature(
3740            "CREATE variable-length relationships are not supported".to_string(),
3741        ));
3742    }
3743
3744    Ok(RelationshipCreatePattern {
3745        start_variable,
3746        end_variable,
3747        relationship: chain.relationship.clone(),
3748    })
3749}
3750
3751fn relationship_create_patterns(pattern: &Pattern) -> Result<Vec<RelationshipCreatePattern>> {
3752    if pattern.shortest_path.is_some() || pattern.chains.is_empty() {
3753        return Err(Error::UnsupportedQueryFeature(
3754            "CREATE relationship currently supports relationship patterns".to_string(),
3755        ));
3756    }
3757
3758    pattern
3759        .chains
3760        .iter()
3761        .map(|chain| {
3762            let start_variable = chain.left_variable.clone().ok_or_else(|| {
3763                Error::Validation("CREATE relationship start node must use a variable".to_string())
3764            })?;
3765            let end_variable = chain.node.variable.clone().ok_or_else(|| {
3766                Error::Validation("CREATE relationship end node must use a variable".to_string())
3767            })?;
3768
3769            if chain.relationship.variable_length {
3770                return Err(Error::UnsupportedQueryFeature(
3771                    "CREATE variable-length relationships are not supported".to_string(),
3772                ));
3773            }
3774
3775            Ok(RelationshipCreatePattern {
3776                start_variable,
3777                end_variable,
3778                relationship: chain.relationship.clone(),
3779            })
3780        })
3781        .collect()
3782}
3783
3784fn relationship_create_type(relationship: &RelationshipPattern) -> Result<String> {
3785    match relationship.types.as_slice() {
3786        [] => Err(Error::Validation(
3787            "CREATE relationship requires a relationship type".to_string(),
3788        )),
3789        [r#type, ..] => Ok(r#type.clone()),
3790    }
3791}
3792
3793fn relationship_properties_with_entities(
3794    storage: &dyn StorageInterface,
3795    ids: &BTreeMap<String, EntityId>,
3796    relationship: &RelationshipPattern,
3797    params: &Params,
3798) -> Result<Properties> {
3799    relationship
3800        .properties
3801        .iter()
3802        .map(|property| {
3803            evaluate_write_expression_with_entities(storage, ids, &property.expression, params)
3804                .map(|value| (property.key.clone(), value))
3805        })
3806        .collect()
3807}
3808
3809fn entity_id_from_external_id(
3810    storage: &dyn StorageInterface,
3811    external_id: &str,
3812    relationship: bool,
3813) -> Result<EntityId> {
3814    if relationship {
3815        if let Some(relationship_id) = storage.relationship_by_external_id(external_id) {
3816            return Ok(EntityId::Relationship(relationship_id));
3817        }
3818    } else if let Some(node_id) = storage.node_by_external_id(external_id) {
3819        return Ok(EntityId::Node(node_id));
3820    }
3821    Err(Error::Validation(
3822        "SET target variable must bind a node or relationship".to_string(),
3823    ))
3824}
3825
3826fn relationship_merge_endpoint_variables(
3827    matches: &[MatchClause],
3828    start_variable: &str,
3829    end_variable: &str,
3830) -> Vec<String> {
3831    let mut variables = Vec::new();
3832    for clause in matches {
3833        for pattern in &clause.patterns {
3834            collect_pattern_entity_variables(pattern, &mut variables);
3835        }
3836    }
3837    push_unique_string(&mut variables, start_variable);
3838    push_unique_string(&mut variables, end_variable);
3839    variables
3840}
3841
3842fn relationship_create_endpoint_variables(patterns: &[RelationshipCreatePattern]) -> Vec<String> {
3843    let mut variables = Vec::new();
3844    for pattern in patterns {
3845        push_unique_string(&mut variables, &pattern.start_variable);
3846        push_unique_string(&mut variables, &pattern.end_variable);
3847    }
3848    variables
3849}
3850
3851fn relationship_create_variables(patterns: &[RelationshipCreatePattern]) -> Vec<String> {
3852    let mut variables = Vec::new();
3853    for pattern in patterns {
3854        if let Some(variable) = &pattern.relationship.variable {
3855            push_unique_string(&mut variables, variable);
3856        }
3857    }
3858    variables
3859}
3860
3861fn collect_pattern_entity_variables(pattern: &Pattern, variables: &mut Vec<String>) {
3862    if let Some(variable) = &pattern.start.variable {
3863        push_unique_string(variables, variable);
3864    }
3865    for chain in &pattern.chains {
3866        if let Some(variable) = &chain.relationship.variable {
3867            push_unique_string(variables, variable);
3868        }
3869        if let Some(variable) = &chain.node.variable {
3870            push_unique_string(variables, variable);
3871        }
3872    }
3873}
3874
3875fn push_unique_string(values: &mut Vec<String>, value: &str) {
3876    if !values.iter().any(|existing| existing == value) {
3877        values.push(value.to_string());
3878    }
3879}
3880
3881fn element_id_return_items(variables: &[String]) -> Vec<ReturnItem> {
3882    variables
3883        .iter()
3884        .map(|variable| ReturnItem {
3885            expression: ReturnExpression::ElementId(variable.clone()),
3886            alias: Some(variable.clone()),
3887        })
3888        .collect()
3889}
3890
3891fn entity_ids_from_row(
3892    storage: &dyn StorageInterface,
3893    columns: &[String],
3894    row: &Record,
3895    relationship_variables: &BTreeSet<String>,
3896) -> Result<BTreeMap<String, EntityId>> {
3897    let mut ids = BTreeMap::new();
3898    for (index, variable) in columns.iter().enumerate() {
3899        match row.values.get(index) {
3900            Some(Value::String(external_id)) => {
3901                ids.insert(
3902                    variable.clone(),
3903                    entity_id_from_external_id(
3904                        storage,
3905                        external_id,
3906                        relationship_variables.contains(variable),
3907                    )?,
3908                );
3909            }
3910            Some(Value::Null) => {}
3911            _ => {
3912                return Err(Error::Validation(
3913                    "relationship endpoints must be matched by node variables".to_string(),
3914                ))
3915            }
3916        }
3917    }
3918    Ok(ids)
3919}
3920
3921fn node_id_from_entities(
3922    ids: &BTreeMap<String, EntityId>,
3923    variable: &str,
3924    role: &str,
3925) -> Result<NodeId> {
3926    match ids.get(variable) {
3927        Some(EntityId::Node(node_id)) => Ok(*node_id),
3928        Some(EntityId::Relationship(_)) => Err(Error::Validation(format!(
3929            "CREATE relationship {role} variable `{variable}` must bind a node"
3930        ))),
3931        None => Err(Error::Validation(format!(
3932            "CREATE relationship {role} node must be matched by variable"
3933        ))),
3934    }
3935}
3936
3937fn evaluate_write_expression(expression: &Expression, params: &Params) -> Result<Value> {
3938    match expression {
3939        Expression::Literal(value) => Ok(value.clone()),
3940        Expression::Operand(Operand::Literal(value)) => Ok(value.clone()),
3941        Expression::Parameter(name) => params
3942            .get(name)
3943            .cloned()
3944            .ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
3945        Expression::Operand(Operand::Parameter(name)) => params
3946            .get(name)
3947            .cloned()
3948            .ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
3949        Expression::Add(left, right) => {
3950            evaluate_write_arithmetic_expression(left, right, WriteArithmeticOperator::Add, params)
3951        }
3952        Expression::Subtract(left, right) => evaluate_write_arithmetic_expression(
3953            left,
3954            right,
3955            WriteArithmeticOperator::Subtract,
3956            params,
3957        ),
3958        Expression::Multiply(left, right) => evaluate_write_arithmetic_expression(
3959            left,
3960            right,
3961            WriteArithmeticOperator::Multiply,
3962            params,
3963        ),
3964        Expression::Divide(left, right) => evaluate_write_arithmetic_expression(
3965            left,
3966            right,
3967            WriteArithmeticOperator::Divide,
3968            params,
3969        ),
3970        Expression::Modulo(left, right) => evaluate_write_arithmetic_expression(
3971            left,
3972            right,
3973            WriteArithmeticOperator::Modulo,
3974            params,
3975        ),
3976        Expression::ToLower(expression) => evaluate_write_string_case_value(
3977            evaluate_write_expression(expression, params)?,
3978            WriteStringCaseFunction::Lower,
3979        ),
3980        Expression::ToUpper(expression) => evaluate_write_string_case_value(
3981            evaluate_write_expression(expression, params)?,
3982            WriteStringCaseFunction::Upper,
3983        ),
3984        Expression::ToString(expression) => {
3985            evaluate_write_to_string_value(evaluate_write_expression(expression, params)?)
3986        }
3987        Expression::ToInteger(expression) => {
3988            evaluate_write_to_integer_value(evaluate_write_expression(expression, params)?)
3989        }
3990        Expression::ToFloat(expression) => {
3991            evaluate_write_to_float_value(evaluate_write_expression(expression, params)?)
3992        }
3993        Expression::ToBoolean(expression) => {
3994            evaluate_write_to_boolean_value(evaluate_write_expression(expression, params)?)
3995        }
3996        Expression::ToStringOrNull(expression) => {
3997            evaluate_write_to_string_or_null_value(evaluate_write_expression(expression, params)?)
3998        }
3999        Expression::ToIntegerOrNull(expression) => {
4000            evaluate_write_to_integer_or_null_value(evaluate_write_expression(expression, params)?)
4001        }
4002        Expression::ToFloatOrNull(expression) => {
4003            evaluate_write_to_float_or_null_value(evaluate_write_expression(expression, params)?)
4004        }
4005        Expression::ToBooleanOrNull(expression) => {
4006            evaluate_write_to_boolean_or_null_value(evaluate_write_expression(expression, params)?)
4007        }
4008        Expression::IsEmpty(expression) => {
4009            evaluate_write_is_empty_value(evaluate_write_expression(expression, params)?)
4010        }
4011        Expression::Head(expression) => {
4012            evaluate_write_head_value(evaluate_write_expression(expression, params)?)
4013        }
4014        Expression::Last(expression) => {
4015            evaluate_write_last_value(evaluate_write_expression(expression, params)?)
4016        }
4017        Expression::Tail(expression) => {
4018            evaluate_write_tail_value(evaluate_write_expression(expression, params)?)
4019        }
4020        Expression::Range { start, end, step } => evaluate_write_range_value(
4021            evaluate_write_expression(start, params)?,
4022            evaluate_write_expression(end, params)?,
4023            step.as_ref()
4024                .map(|step| evaluate_write_expression(step, params))
4025                .transpose()?,
4026            None,
4027        ),
4028        Expression::ListIndex { value, index } => evaluate_write_list_index_value(
4029            evaluate_write_expression(value, params)?,
4030            evaluate_write_expression(index, params)?,
4031        ),
4032        Expression::ListSlice { value, start, end } => evaluate_write_list_slice_value(
4033            evaluate_write_expression(value, params)?,
4034            start
4035                .as_ref()
4036                .map(|start| evaluate_write_expression(start, params))
4037                .transpose()?,
4038            end.as_ref()
4039                .map(|end| evaluate_write_expression(end, params))
4040                .transpose()?,
4041        ),
4042        Expression::Size(expression) => {
4043            evaluate_write_size_value(evaluate_write_expression(expression, params)?)
4044        }
4045        Expression::Substring {
4046            value,
4047            start,
4048            length,
4049        } => evaluate_write_substring_value(
4050            evaluate_write_expression(value, params)?,
4051            evaluate_write_expression(start, params)?,
4052            length
4053                .as_ref()
4054                .map(|length| evaluate_write_expression(length, params))
4055                .transpose()?,
4056        ),
4057        Expression::Replace {
4058            value,
4059            search,
4060            replacement,
4061        } => evaluate_write_replace_value(
4062            evaluate_write_expression(value, params)?,
4063            evaluate_write_expression(search, params)?,
4064            evaluate_write_expression(replacement, params)?,
4065        ),
4066        Expression::Trim { mode, expression } => {
4067            evaluate_write_trim_value(evaluate_write_expression(expression, params)?, mode)
4068        }
4069        Expression::Split { value, delimiter } => evaluate_write_split_value(
4070            evaluate_write_expression(value, params)?,
4071            evaluate_write_expression(delimiter, params)?,
4072        ),
4073        Expression::StringSlice {
4074            mode,
4075            value,
4076            length,
4077        } => evaluate_write_string_slice_value(
4078            evaluate_write_expression(value, params)?,
4079            evaluate_write_expression(length, params)?,
4080            mode,
4081        ),
4082        Expression::Reverse(expression) => {
4083            evaluate_write_reverse_value(evaluate_write_expression(expression, params)?)
4084        }
4085        Expression::Abs(expression) => {
4086            evaluate_write_abs_value(evaluate_write_expression(expression, params)?)
4087        }
4088        Expression::Rounding { mode, expression } => {
4089            evaluate_write_rounding_value(evaluate_write_expression(expression, params)?, mode)
4090        }
4091        Expression::Sign(expression) => {
4092            evaluate_write_sign_value(evaluate_write_expression(expression, params)?)
4093        }
4094        Expression::Sqrt(expression) => {
4095            evaluate_write_sqrt_value(evaluate_write_expression(expression, params)?)
4096        }
4097        Expression::Round(expression) => {
4098            evaluate_write_round_value(evaluate_write_expression(expression, params)?)
4099        }
4100        Expression::Log(expression) => {
4101            evaluate_write_log_value(evaluate_write_expression(expression, params)?)
4102        }
4103        Expression::Log10(expression) => {
4104            evaluate_write_log10_value(evaluate_write_expression(expression, params)?)
4105        }
4106        Expression::Exp(expression) => {
4107            evaluate_write_exp_value(evaluate_write_expression(expression, params)?)
4108        }
4109        Expression::AngleConversion { mode, expression } => evaluate_write_angle_conversion_value(
4110            evaluate_write_expression(expression, params)?,
4111            mode,
4112        ),
4113        Expression::Trigonometric { mode, expression } => {
4114            evaluate_write_trigonometric_value(evaluate_write_expression(expression, params)?, mode)
4115        }
4116        Expression::InverseTrigonometric { mode, expression } => {
4117            evaluate_write_inverse_trigonometric_value(
4118                evaluate_write_expression(expression, params)?,
4119                mode,
4120            )
4121        }
4122        Expression::Atan2 { y, x } => evaluate_write_atan2_value(
4123            evaluate_write_expression(y, params)?,
4124            evaluate_write_expression(x, params)?,
4125        ),
4126        Expression::Haversin(expression) => {
4127            evaluate_write_haversin_value(evaluate_write_expression(expression, params)?)
4128        }
4129        Expression::Pi => Ok(Value::Float(std::f64::consts::PI)),
4130        Expression::E => Ok(Value::Float(std::f64::consts::E)),
4131        Expression::List(items) => items
4132            .iter()
4133            .map(|item| evaluate_write_expression(item, params))
4134            .collect::<Result<Vec<_>>>()
4135            .map(Value::List),
4136        Expression::ListComprehension {
4137            variable,
4138            list,
4139            predicate,
4140            projection,
4141        } => evaluate_contextless_write_list_comprehension(
4142            variable,
4143            evaluate_write_expression(list, params)?,
4144            predicate.as_deref(),
4145            projection,
4146            params,
4147        ),
4148        Expression::ListPredicate {
4149            mode,
4150            variable,
4151            list,
4152            predicate,
4153        } => evaluate_contextless_write_list_predicate(
4154            *mode,
4155            variable,
4156            evaluate_write_expression(list, params)?,
4157            predicate,
4158            params,
4159        ),
4160        Expression::Reduce {
4161            accumulator,
4162            initial,
4163            variable,
4164            list,
4165            expression,
4166        } => evaluate_contextless_write_reduce(
4167            accumulator,
4168            evaluate_write_expression(initial, params)?,
4169            variable,
4170            evaluate_write_expression(list, params)?,
4171            expression,
4172            params,
4173        ),
4174        Expression::Map(entries) => entries
4175            .iter()
4176            .map(|(key, expression)| {
4177                evaluate_write_expression(expression, params).map(|value| (key.clone(), value))
4178            })
4179            .collect::<Result<BTreeMap<_, _>>>()
4180            .map(Value::Map),
4181        Expression::Coalesce(items) => {
4182            for item in items {
4183                let value = evaluate_write_expression(item, params)?;
4184                if value != Value::Null {
4185                    return Ok(value);
4186                }
4187            }
4188            Ok(Value::Null)
4189        }
4190        Expression::Case {
4191            alternatives,
4192            else_expression,
4193        } => {
4194            for alternative in alternatives {
4195                if evaluate_contextless_write_predicate(&alternative.predicate, params)? {
4196                    return evaluate_write_expression(&alternative.expression, params);
4197                }
4198            }
4199
4200            evaluate_write_expression(else_expression, params)
4201        }
4202        Expression::SimpleCase {
4203            operand,
4204            alternatives,
4205            else_expression,
4206        } => {
4207            let operand = evaluate_write_expression(operand, params)?;
4208            for alternative in alternatives {
4209                let value = evaluate_write_expression(&alternative.value, params)?;
4210                if compare_write_values(&operand, ComparisonOperator::Equal, &value) {
4211                    return evaluate_write_expression(&alternative.expression, params);
4212                }
4213            }
4214
4215            evaluate_write_expression(else_expression, params)
4216        }
4217        Expression::Predicate(predicate) => {
4218            evaluate_contextless_write_predicate(predicate, params).map(Value::Boolean)
4219        }
4220        _ => Err(Error::UnsupportedQueryFeature(
4221            "write property values currently support literal and parameter values".to_string(),
4222        )),
4223    }
4224}
4225
4226fn evaluate_contextless_write_predicate(predicate: &Predicate, params: &Params) -> Result<bool> {
4227    match predicate {
4228        Predicate::Comparison {
4229            left,
4230            operator,
4231            right,
4232        } => {
4233            let left = evaluate_write_expression(left, params)?;
4234            let right = evaluate_write_expression(right, params)?;
4235            Ok(compare_write_values(&left, *operator, &right))
4236        }
4237        Predicate::In { item, list } => {
4238            let item = evaluate_write_expression(item, params)?;
4239            let list = evaluate_write_expression(list, params)?;
4240            evaluate_write_in_predicate(list, item, None)
4241        }
4242        Predicate::StringMatch {
4243            left,
4244            operator,
4245            right,
4246        } => {
4247            let left = evaluate_write_expression(left, params)?;
4248            let right = evaluate_write_expression(right, params)?;
4249            evaluate_write_string_predicate(&left, *operator, &right)
4250        }
4251        Predicate::And(left, right) => Ok(evaluate_contextless_write_predicate(left, params)?
4252            && evaluate_contextless_write_predicate(right, params)?),
4253        Predicate::Or(left, right) => Ok(evaluate_contextless_write_predicate(left, params)?
4254            || evaluate_contextless_write_predicate(right, params)?),
4255        Predicate::Xor(left, right) => Ok(evaluate_contextless_write_predicate(left, params)?
4256            ^ evaluate_contextless_write_predicate(right, params)?),
4257        Predicate::Not(inner) => Ok(!evaluate_contextless_write_predicate(inner, params)?),
4258        Predicate::Pattern(_) => Err(Error::UnsupportedQueryFeature(
4259            "pattern predicates require a matched row context".to_string(),
4260        )),
4261        Predicate::IsNull(expression) => {
4262            Ok(evaluate_write_expression(expression, params)? == Value::Null)
4263        }
4264        Predicate::IsNotNull(expression) => {
4265            Ok(evaluate_write_expression(expression, params)? != Value::Null)
4266        }
4267        Predicate::Exists(operand) => {
4268            Ok(evaluate_contextless_write_operand(operand, params)? != Value::Null)
4269        }
4270        Predicate::ExistsSubquery(_) => Err(Error::UnsupportedQueryFeature(
4271            "write expressions do not support EXISTS subqueries without a matched row context"
4272                .to_string(),
4273        )),
4274        Predicate::Boolean(expression) => match evaluate_write_expression(expression, params)? {
4275            Value::Boolean(value) => Ok(value),
4276            Value::Null => Ok(false),
4277            _ => Err(Error::Validation(
4278                "bare operands must evaluate to boolean".to_string(),
4279            )),
4280        },
4281    }
4282}
4283
4284fn evaluate_contextless_write_operand(operand: &Operand, params: &Params) -> Result<Value> {
4285    match operand {
4286        Operand::Literal(value) => Ok(value.clone()),
4287        Operand::Parameter(name) => params
4288            .get(name)
4289            .cloned()
4290            .ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
4291        Operand::Property { .. } | Operand::DynamicProperty { .. } | Operand::Variable(_) => Err(
4292            Error::Validation("write property expression variable is not bound".to_string()),
4293        ),
4294    }
4295}
4296
4297fn evaluate_write_expression_with_entities(
4298    storage: &dyn StorageInterface,
4299    ids: &BTreeMap<String, EntityId>,
4300    expression: &Expression,
4301    params: &Params,
4302) -> Result<Value> {
4303    match expression {
4304        Expression::Operand(Operand::Property { variable, key }) => {
4305            entity_property_value(storage, ids, variable, key)
4306        }
4307        Expression::Operand(Operand::DynamicProperty { variable, key }) => {
4308            let key = evaluate_write_expression_with_entities(storage, ids, key, params)?;
4309            let Value::String(key) = key else {
4310                return Err(Error::Validation(
4311                    "dynamic property keys must evaluate to strings".to_string(),
4312                ));
4313            };
4314            entity_property_value(storage, ids, variable, &key)
4315        }
4316        Expression::Add(left, right) => evaluate_write_arithmetic_expression_with_entities(
4317            storage,
4318            ids,
4319            left,
4320            right,
4321            WriteArithmeticOperator::Add,
4322            params,
4323        ),
4324        Expression::Subtract(left, right) => evaluate_write_arithmetic_expression_with_entities(
4325            storage,
4326            ids,
4327            left,
4328            right,
4329            WriteArithmeticOperator::Subtract,
4330            params,
4331        ),
4332        Expression::Multiply(left, right) => evaluate_write_arithmetic_expression_with_entities(
4333            storage,
4334            ids,
4335            left,
4336            right,
4337            WriteArithmeticOperator::Multiply,
4338            params,
4339        ),
4340        Expression::Divide(left, right) => evaluate_write_arithmetic_expression_with_entities(
4341            storage,
4342            ids,
4343            left,
4344            right,
4345            WriteArithmeticOperator::Divide,
4346            params,
4347        ),
4348        Expression::Modulo(left, right) => evaluate_write_arithmetic_expression_with_entities(
4349            storage,
4350            ids,
4351            left,
4352            right,
4353            WriteArithmeticOperator::Modulo,
4354            params,
4355        ),
4356        Expression::ToLower(expression) => evaluate_write_string_case_value(
4357            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4358            WriteStringCaseFunction::Lower,
4359        ),
4360        Expression::ToUpper(expression) => evaluate_write_string_case_value(
4361            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4362            WriteStringCaseFunction::Upper,
4363        ),
4364        Expression::ToString(expression) => evaluate_write_to_string_value(
4365            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4366        ),
4367        Expression::ToInteger(expression) => evaluate_write_to_integer_value(
4368            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4369        ),
4370        Expression::ToFloat(expression) => evaluate_write_to_float_value(
4371            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4372        ),
4373        Expression::ToBoolean(expression) => evaluate_write_to_boolean_value(
4374            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4375        ),
4376        Expression::ToStringOrNull(expression) => evaluate_write_to_string_or_null_value(
4377            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4378        ),
4379        Expression::ToIntegerOrNull(expression) => evaluate_write_to_integer_or_null_value(
4380            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4381        ),
4382        Expression::ToFloatOrNull(expression) => evaluate_write_to_float_or_null_value(
4383            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4384        ),
4385        Expression::ToBooleanOrNull(expression) => evaluate_write_to_boolean_or_null_value(
4386            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4387        ),
4388        Expression::IsEmpty(expression) => evaluate_write_is_empty_value(
4389            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4390        ),
4391        Expression::Head(expression) => evaluate_write_head_value(
4392            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4393        ),
4394        Expression::Last(expression) => evaluate_write_last_value(
4395            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4396        ),
4397        Expression::Tail(expression) => evaluate_write_tail_value(
4398            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4399        ),
4400        Expression::Range { start, end, step } => evaluate_write_range_value(
4401            evaluate_write_expression_with_entities(storage, ids, start, params)?,
4402            evaluate_write_expression_with_entities(storage, ids, end, params)?,
4403            step.as_ref()
4404                .map(|step| evaluate_write_expression_with_entities(storage, ids, step, params))
4405                .transpose()?,
4406            Some(storage),
4407        ),
4408        Expression::ListIndex { value, index } => evaluate_write_list_index_value(
4409            evaluate_write_expression_with_entities(storage, ids, value, params)?,
4410            evaluate_write_expression_with_entities(storage, ids, index, params)?,
4411        ),
4412        Expression::ListSlice { value, start, end } => evaluate_write_list_slice_value(
4413            evaluate_write_expression_with_entities(storage, ids, value, params)?,
4414            start
4415                .as_ref()
4416                .map(|start| evaluate_write_expression_with_entities(storage, ids, start, params))
4417                .transpose()?,
4418            end.as_ref()
4419                .map(|end| evaluate_write_expression_with_entities(storage, ids, end, params))
4420                .transpose()?,
4421        ),
4422        Expression::Size(expression) => evaluate_write_size_value(
4423            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4424        ),
4425        Expression::Substring {
4426            value,
4427            start,
4428            length,
4429        } => evaluate_write_substring_value(
4430            evaluate_write_expression_with_entities(storage, ids, value, params)?,
4431            evaluate_write_expression_with_entities(storage, ids, start, params)?,
4432            length
4433                .as_ref()
4434                .map(|length| evaluate_write_expression_with_entities(storage, ids, length, params))
4435                .transpose()?,
4436        ),
4437        Expression::Replace {
4438            value,
4439            search,
4440            replacement,
4441        } => evaluate_write_replace_value(
4442            evaluate_write_expression_with_entities(storage, ids, value, params)?,
4443            evaluate_write_expression_with_entities(storage, ids, search, params)?,
4444            evaluate_write_expression_with_entities(storage, ids, replacement, params)?,
4445        ),
4446        Expression::Trim { mode, expression } => evaluate_write_trim_value(
4447            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4448            mode,
4449        ),
4450        Expression::Split { value, delimiter } => evaluate_write_split_value(
4451            evaluate_write_expression_with_entities(storage, ids, value, params)?,
4452            evaluate_write_expression_with_entities(storage, ids, delimiter, params)?,
4453        ),
4454        Expression::StringSlice {
4455            mode,
4456            value,
4457            length,
4458        } => evaluate_write_string_slice_value(
4459            evaluate_write_expression_with_entities(storage, ids, value, params)?,
4460            evaluate_write_expression_with_entities(storage, ids, length, params)?,
4461            mode,
4462        ),
4463        Expression::Reverse(expression) => evaluate_write_reverse_value(
4464            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4465        ),
4466        Expression::Abs(expression) => evaluate_write_abs_value(
4467            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4468        ),
4469        Expression::Rounding { mode, expression } => evaluate_write_rounding_value(
4470            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4471            mode,
4472        ),
4473        Expression::Sign(expression) => evaluate_write_sign_value(
4474            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4475        ),
4476        Expression::Sqrt(expression) => evaluate_write_sqrt_value(
4477            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4478        ),
4479        Expression::Round(expression) => evaluate_write_round_value(
4480            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4481        ),
4482        Expression::Log(expression) => evaluate_write_log_value(
4483            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4484        ),
4485        Expression::Log10(expression) => evaluate_write_log10_value(
4486            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4487        ),
4488        Expression::Exp(expression) => evaluate_write_exp_value(
4489            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4490        ),
4491        Expression::AngleConversion { mode, expression } => evaluate_write_angle_conversion_value(
4492            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4493            mode,
4494        ),
4495        Expression::Trigonometric { mode, expression } => evaluate_write_trigonometric_value(
4496            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4497            mode,
4498        ),
4499        Expression::InverseTrigonometric { mode, expression } => {
4500            evaluate_write_inverse_trigonometric_value(
4501                evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4502                mode,
4503            )
4504        }
4505        Expression::Atan2 { y, x } => evaluate_write_atan2_value(
4506            evaluate_write_expression_with_entities(storage, ids, y, params)?,
4507            evaluate_write_expression_with_entities(storage, ids, x, params)?,
4508        ),
4509        Expression::Haversin(expression) => evaluate_write_haversin_value(
4510            evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4511        ),
4512        Expression::Pi => Ok(Value::Float(std::f64::consts::PI)),
4513        Expression::E => Ok(Value::Float(std::f64::consts::E)),
4514        Expression::List(items) => items
4515            .iter()
4516            .map(|item| evaluate_write_expression_with_entities(storage, ids, item, params))
4517            .collect::<Result<Vec<_>>>()
4518            .map(Value::List),
4519        Expression::ListComprehension {
4520            variable,
4521            list,
4522            predicate,
4523            projection,
4524        } => evaluate_write_list_comprehension_with_entities(
4525            storage,
4526            ids,
4527            variable,
4528            evaluate_write_expression_with_entities(storage, ids, list, params)?,
4529            predicate.as_deref(),
4530            projection,
4531            params,
4532        ),
4533        Expression::ListPredicate {
4534            mode,
4535            variable,
4536            list,
4537            predicate,
4538        } => evaluate_write_list_predicate_with_entities(
4539            storage,
4540            ids,
4541            *mode,
4542            variable,
4543            evaluate_write_expression_with_entities(storage, ids, list, params)?,
4544            predicate,
4545            params,
4546        ),
4547        Expression::Reduce {
4548            accumulator,
4549            initial,
4550            variable,
4551            list,
4552            expression,
4553        } => evaluate_write_reduce_with_entities(
4554            storage,
4555            ids,
4556            accumulator,
4557            evaluate_write_expression_with_entities(storage, ids, initial, params)?,
4558            variable,
4559            evaluate_write_expression_with_entities(storage, ids, list, params)?,
4560            expression,
4561            params,
4562        ),
4563        Expression::Map(entries) => entries
4564            .iter()
4565            .map(|(key, expression)| {
4566                evaluate_write_expression_with_entities(storage, ids, expression, params)
4567                    .map(|value| (key.clone(), value))
4568            })
4569            .collect::<Result<BTreeMap<_, _>>>()
4570            .map(Value::Map),
4571        Expression::MapProjection { variable, items } => {
4572            evaluate_write_map_projection(storage, ids, variable, items, params)
4573        }
4574        Expression::PatternComprehension {
4575            pattern,
4576            predicate,
4577            projection,
4578        } => evaluate_write_pattern_comprehension(
4579            storage,
4580            ids,
4581            pattern,
4582            predicate.as_deref(),
4583            projection,
4584            params,
4585        ),
4586        Expression::Coalesce(items) => {
4587            for item in items {
4588                let value = evaluate_write_expression_with_entities(storage, ids, item, params)?;
4589                if value != Value::Null {
4590                    return Ok(value);
4591                }
4592            }
4593            Ok(Value::Null)
4594        }
4595        Expression::Case {
4596            alternatives,
4597            else_expression,
4598        } => {
4599            for alternative in alternatives {
4600                if evaluate_write_predicate(storage, ids, &alternative.predicate, params)? {
4601                    return evaluate_write_expression_with_entities(
4602                        storage,
4603                        ids,
4604                        &alternative.expression,
4605                        params,
4606                    );
4607                }
4608            }
4609
4610            evaluate_write_expression_with_entities(storage, ids, else_expression, params)
4611        }
4612        Expression::SimpleCase {
4613            operand,
4614            alternatives,
4615            else_expression,
4616        } => {
4617            let operand = evaluate_write_expression_with_entities(storage, ids, operand, params)?;
4618            for alternative in alternatives {
4619                let value = evaluate_write_expression_with_entities(
4620                    storage,
4621                    ids,
4622                    &alternative.value,
4623                    params,
4624                )?;
4625                if compare_write_values(&operand, ComparisonOperator::Equal, &value) {
4626                    return evaluate_write_expression_with_entities(
4627                        storage,
4628                        ids,
4629                        &alternative.expression,
4630                        params,
4631                    );
4632                }
4633            }
4634
4635            evaluate_write_expression_with_entities(storage, ids, else_expression, params)
4636        }
4637        Expression::Predicate(predicate) => {
4638            evaluate_write_predicate(storage, ids, predicate, params).map(Value::Boolean)
4639        }
4640        _ => evaluate_write_expression(expression, params),
4641    }
4642}
4643
4644fn evaluate_contextless_write_list_comprehension(
4645    variable: &str,
4646    list: Value,
4647    predicate: Option<&Predicate>,
4648    projection: &Expression,
4649    params: &Params,
4650) -> Result<Value> {
4651    let Value::List(values) = list else {
4652        return if list == Value::Null {
4653            Ok(Value::Null)
4654        } else {
4655            Err(Error::Validation(
4656                "list comprehension requires a list argument".to_string(),
4657            ))
4658        };
4659    };
4660
4661    let mut output = Vec::new();
4662    for value in values {
4663        if let Some(predicate) = predicate {
4664            let predicate = substitute_predicate_value(predicate, variable, &value);
4665            if !evaluate_contextless_write_predicate(&predicate, params)? {
4666                continue;
4667            }
4668        }
4669
4670        let projection = substitute_expression_value(projection, variable, &value);
4671        output.push(evaluate_write_expression(&projection, params)?);
4672    }
4673
4674    Ok(Value::List(output))
4675}
4676
4677fn evaluate_contextless_write_list_predicate(
4678    mode: crate::cypher::ast::ListPredicateMode,
4679    variable: &str,
4680    list: Value,
4681    predicate: &Predicate,
4682    params: &Params,
4683) -> Result<Value> {
4684    let Value::List(values) = list else {
4685        return if list == Value::Null {
4686            Ok(Value::Null)
4687        } else {
4688            Err(Error::Validation(
4689                "list predicate functions require a list argument".to_string(),
4690            ))
4691        };
4692    };
4693
4694    let mut matches = 0usize;
4695    for value in &values {
4696        let predicate = substitute_predicate_value(predicate, variable, value);
4697        if evaluate_contextless_write_predicate(&predicate, params)? {
4698            matches += 1;
4699        }
4700    }
4701
4702    Ok(Value::Boolean(write_list_predicate_result(
4703        mode,
4704        matches,
4705        values.len(),
4706    )))
4707}
4708
4709fn evaluate_contextless_write_reduce(
4710    accumulator: &str,
4711    initial: Value,
4712    variable: &str,
4713    list: Value,
4714    expression: &Expression,
4715    params: &Params,
4716) -> Result<Value> {
4717    let Value::List(values) = list else {
4718        return if list == Value::Null {
4719            Ok(Value::Null)
4720        } else {
4721            Err(Error::Validation(
4722                "reduce requires a list argument".to_string(),
4723            ))
4724        };
4725    };
4726
4727    let mut accumulator_value = initial;
4728    for value in values {
4729        let expression = substitute_expression_value(expression, accumulator, &accumulator_value);
4730        let expression = substitute_expression_value(&expression, variable, &value);
4731        accumulator_value = evaluate_write_expression(&expression, params)?;
4732    }
4733
4734    Ok(accumulator_value)
4735}
4736
4737fn evaluate_write_map_projection(
4738    storage: &dyn StorageInterface,
4739    ids: &BTreeMap<String, EntityId>,
4740    variable: &str,
4741    items: &[crate::cypher::ast::MapProjectionItem],
4742    params: &Params,
4743) -> Result<Value> {
4744    let mut values = BTreeMap::new();
4745    for item in items {
4746        match item {
4747            crate::cypher::ast::MapProjectionItem::AllProperties => {
4748                values.extend(entity_properties(storage, ids, variable)?);
4749            }
4750            crate::cypher::ast::MapProjectionItem::Property(key) => {
4751                values.insert(
4752                    key.clone(),
4753                    entity_property_value(storage, ids, variable, key)?,
4754                );
4755            }
4756            crate::cypher::ast::MapProjectionItem::Variable(variable) => {
4757                values.insert(
4758                    variable.clone(),
4759                    evaluate_write_operand(
4760                        storage,
4761                        ids,
4762                        &Operand::Variable(variable.clone()),
4763                        params,
4764                    )?,
4765                );
4766            }
4767            crate::cypher::ast::MapProjectionItem::Expression { key, expression } => {
4768                values.insert(
4769                    key.clone(),
4770                    evaluate_write_expression_with_entities(storage, ids, expression, params)?,
4771                );
4772            }
4773        }
4774    }
4775
4776    Ok(Value::Map(values))
4777}
4778
4779fn evaluate_write_list_comprehension_with_entities(
4780    storage: &dyn StorageInterface,
4781    ids: &BTreeMap<String, EntityId>,
4782    variable: &str,
4783    list: Value,
4784    predicate: Option<&Predicate>,
4785    projection: &Expression,
4786    params: &Params,
4787) -> Result<Value> {
4788    let Value::List(values) = list else {
4789        return if list == Value::Null {
4790            Ok(Value::Null)
4791        } else {
4792            Err(Error::Validation(
4793                "list comprehension requires a list argument".to_string(),
4794            ))
4795        };
4796    };
4797
4798    let mut output = Vec::new();
4799    for (index, value) in values.into_iter().enumerate() {
4800        if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
4801            storage.check_query_control()?;
4802        }
4803        if let Some(predicate) = predicate {
4804            let predicate = substitute_predicate_value(predicate, variable, &value);
4805            if !evaluate_write_predicate(storage, ids, &predicate, params)? {
4806                continue;
4807            }
4808        }
4809
4810        let projection = substitute_expression_value(projection, variable, &value);
4811        output.push(evaluate_write_expression_with_entities(
4812            storage,
4813            ids,
4814            &projection,
4815            params,
4816        )?);
4817    }
4818
4819    Ok(Value::List(output))
4820}
4821
4822fn evaluate_write_pattern_comprehension(
4823    storage: &dyn StorageInterface,
4824    ids: &BTreeMap<String, EntityId>,
4825    pattern: &Pattern,
4826    predicate: Option<&Predicate>,
4827    projection: &Expression,
4828    params: &Params,
4829) -> Result<Value> {
4830    if pattern.variable.is_some() || pattern.shortest_path.is_some() || pattern.chains.len() != 1 {
4831        return Err(Error::UnsupportedQueryFeature(
4832            "write pattern comprehension currently supports a single relationship pattern"
4833                .to_string(),
4834        ));
4835    }
4836    let chain = &pattern.chains[0];
4837    if chain.relationship.variable_length {
4838        return Err(Error::UnsupportedQueryFeature(
4839            "write pattern comprehension currently supports typed single-hop relationships"
4840                .to_string(),
4841        ));
4842    }
4843
4844    let start_id = write_optional_node_binding(ids, pattern.start.variable.as_deref())?;
4845    let end_id = write_optional_node_binding(ids, chain.node.variable.as_deref())?;
4846    let anchor_id = start_id.or(end_id).ok_or_else(|| {
4847        Error::Execution("pattern comprehension is missing a bound endpoint".to_string())
4848    })?;
4849
4850    storage.check_query_control()?;
4851    let relationship_ids = match (start_id.is_some(), chain.relationship.direction) {
4852        (true, Direction::Outgoing) | (false, Direction::Incoming) => {
4853            storage.outgoing_relationships(anchor_id).to_vec()
4854        }
4855        (true, Direction::Incoming) | (false, Direction::Outgoing) => {
4856            storage.incoming_relationships(anchor_id).to_vec()
4857        }
4858        (_, Direction::Undirected) => storage
4859            .outgoing_relationships(anchor_id)
4860            .iter()
4861            .chain(storage.incoming_relationships(anchor_id))
4862            .copied()
4863            .collect::<Vec<_>>(),
4864    };
4865
4866    let mut values = Vec::new();
4867    for (index, relationship_id) in relationship_ids.into_iter().enumerate() {
4868        if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
4869            storage.check_query_control()?;
4870        }
4871        let relationship = storage.relationship(relationship_id).ok_or_else(|| {
4872            Error::Execution(format!("relationship id {relationship_id} does not exist"))
4873        })?;
4874        if !write_relationship_matches(storage, ids, relationship, &chain.relationship, params)? {
4875            continue;
4876        }
4877
4878        let (candidate_start, candidate_end) = match chain.relationship.direction {
4879            Direction::Outgoing => (relationship.start, relationship.end),
4880            Direction::Incoming => (relationship.end, relationship.start),
4881            Direction::Undirected => {
4882                if start_id == Some(relationship.start) || end_id == Some(relationship.end) {
4883                    (relationship.start, relationship.end)
4884                } else {
4885                    (relationship.end, relationship.start)
4886                }
4887            }
4888        };
4889
4890        if start_id.is_some_and(|node_id| node_id != candidate_start)
4891            || end_id.is_some_and(|node_id| node_id != candidate_end)
4892        {
4893            continue;
4894        }
4895
4896        let mut row_ids = ids.clone();
4897        if let Some(variable) = &pattern.start.variable {
4898            row_ids
4899                .entry(variable.clone())
4900                .or_insert(EntityId::Node(candidate_start));
4901        }
4902        if let Some(variable) = &chain.relationship.variable {
4903            match row_ids.get(variable) {
4904                Some(EntityId::Relationship(bound_id)) if *bound_id == relationship_id => {}
4905                Some(EntityId::Relationship(_)) => continue,
4906                Some(EntityId::Node(_)) => continue,
4907                None => {
4908                    row_ids.insert(variable.clone(), EntityId::Relationship(relationship_id));
4909                }
4910            }
4911        }
4912        if let Some(variable) = &chain.node.variable {
4913            row_ids
4914                .entry(variable.clone())
4915                .or_insert(EntityId::Node(candidate_end));
4916        }
4917
4918        let start_node = storage
4919            .node(candidate_start)
4920            .ok_or_else(|| Error::Execution(format!("node id {candidate_start} does not exist")))?;
4921        let end_node = storage
4922            .node(candidate_end)
4923            .ok_or_else(|| Error::Execution(format!("node id {candidate_end} does not exist")))?;
4924        if !write_node_matches(storage, &row_ids, start_node, &pattern.start, params)?
4925            || !write_node_matches(storage, &row_ids, end_node, &chain.node, params)?
4926        {
4927            continue;
4928        }
4929
4930        if let Some(predicate) = predicate {
4931            if !evaluate_write_predicate(storage, &row_ids, predicate, params)? {
4932                continue;
4933            }
4934        }
4935
4936        values.push(evaluate_write_expression_with_entities(
4937            storage, &row_ids, projection, params,
4938        )?);
4939    }
4940
4941    Ok(Value::List(values))
4942}
4943
4944fn evaluate_write_list_predicate_with_entities(
4945    storage: &dyn StorageInterface,
4946    ids: &BTreeMap<String, EntityId>,
4947    mode: crate::cypher::ast::ListPredicateMode,
4948    variable: &str,
4949    list: Value,
4950    predicate: &Predicate,
4951    params: &Params,
4952) -> Result<Value> {
4953    let Value::List(values) = list else {
4954        return if list == Value::Null {
4955            Ok(Value::Null)
4956        } else {
4957            Err(Error::Validation(
4958                "list predicate functions require a list argument".to_string(),
4959            ))
4960        };
4961    };
4962
4963    let mut matches = 0usize;
4964    for (index, value) in values.iter().enumerate() {
4965        if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
4966            storage.check_query_control()?;
4967        }
4968        let predicate = substitute_predicate_value(predicate, variable, value);
4969        if evaluate_write_predicate(storage, ids, &predicate, params)? {
4970            matches += 1;
4971        }
4972    }
4973
4974    Ok(Value::Boolean(write_list_predicate_result(
4975        mode,
4976        matches,
4977        values.len(),
4978    )))
4979}
4980
4981#[allow(clippy::too_many_arguments)]
4982fn evaluate_write_reduce_with_entities(
4983    storage: &dyn StorageInterface,
4984    ids: &BTreeMap<String, EntityId>,
4985    accumulator: &str,
4986    initial: Value,
4987    variable: &str,
4988    list: Value,
4989    expression: &Expression,
4990    params: &Params,
4991) -> Result<Value> {
4992    let Value::List(values) = list else {
4993        return if list == Value::Null {
4994            Ok(Value::Null)
4995        } else {
4996            Err(Error::Validation(
4997                "reduce requires a list argument".to_string(),
4998            ))
4999        };
5000    };
5001
5002    let mut accumulator_value = initial;
5003    for (index, value) in values.into_iter().enumerate() {
5004        if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
5005            storage.check_query_control()?;
5006        }
5007        let expression = substitute_expression_value(expression, accumulator, &accumulator_value);
5008        let expression = substitute_expression_value(&expression, variable, &value);
5009        accumulator_value =
5010            evaluate_write_expression_with_entities(storage, ids, &expression, params)?;
5011    }
5012
5013    Ok(accumulator_value)
5014}
5015
5016fn write_list_predicate_result(
5017    mode: crate::cypher::ast::ListPredicateMode,
5018    matches: usize,
5019    len: usize,
5020) -> bool {
5021    match mode {
5022        crate::cypher::ast::ListPredicateMode::All => matches == len,
5023        crate::cypher::ast::ListPredicateMode::Any => matches > 0,
5024        crate::cypher::ast::ListPredicateMode::None => matches == 0,
5025        crate::cypher::ast::ListPredicateMode::Single => matches == 1,
5026    }
5027}
5028
5029fn evaluate_write_predicate(
5030    storage: &dyn StorageInterface,
5031    ids: &BTreeMap<String, EntityId>,
5032    predicate: &Predicate,
5033    params: &Params,
5034) -> Result<bool> {
5035    match predicate {
5036        Predicate::Comparison {
5037            left,
5038            operator,
5039            right,
5040        } => {
5041            let left = evaluate_write_expression_with_entities(storage, ids, left, params)?;
5042            let right = evaluate_write_expression_with_entities(storage, ids, right, params)?;
5043            Ok(compare_write_values(&left, *operator, &right))
5044        }
5045        Predicate::In { item, list } => {
5046            let item = evaluate_write_expression_with_entities(storage, ids, item, params)?;
5047            let list = evaluate_write_expression_with_entities(storage, ids, list, params)?;
5048            evaluate_write_in_predicate(list, item, Some(storage))
5049        }
5050        Predicate::StringMatch {
5051            left,
5052            operator,
5053            right,
5054        } => {
5055            let left = evaluate_write_expression_with_entities(storage, ids, left, params)?;
5056            let right = evaluate_write_expression_with_entities(storage, ids, right, params)?;
5057            evaluate_write_string_predicate(&left, *operator, &right)
5058        }
5059        Predicate::And(left, right) => Ok(evaluate_write_predicate(storage, ids, left, params)?
5060            && evaluate_write_predicate(storage, ids, right, params)?),
5061        Predicate::Or(left, right) => Ok(evaluate_write_predicate(storage, ids, left, params)?
5062            || evaluate_write_predicate(storage, ids, right, params)?),
5063        Predicate::Xor(left, right) => Ok(evaluate_write_predicate(storage, ids, left, params)?
5064            ^ evaluate_write_predicate(storage, ids, right, params)?),
5065        Predicate::Not(inner) => Ok(!evaluate_write_predicate(storage, ids, inner, params)?),
5066        Predicate::Pattern(pattern) => {
5067            evaluate_write_pattern_predicate(storage, ids, pattern, params)
5068        }
5069        Predicate::IsNull(expression) => Ok(evaluate_write_expression_with_entities(
5070            storage, ids, expression, params,
5071        )? == Value::Null),
5072        Predicate::IsNotNull(expression) => Ok(evaluate_write_expression_with_entities(
5073            storage, ids, expression, params,
5074        )? != Value::Null),
5075        Predicate::Exists(operand) => {
5076            Ok(evaluate_write_operand(storage, ids, operand, params)? != Value::Null)
5077        }
5078        Predicate::ExistsSubquery(matches) => {
5079            evaluate_write_exists_subquery(storage, ids, matches, params)
5080        }
5081        Predicate::Boolean(expression) => {
5082            match evaluate_write_expression_with_entities(storage, ids, expression, params)? {
5083                Value::Boolean(value) => Ok(value),
5084                Value::Null => Ok(false),
5085                _ => Err(Error::Validation(
5086                    "bare operands must evaluate to boolean".to_string(),
5087                )),
5088            }
5089        }
5090    }
5091}
5092
5093fn evaluate_write_pattern_predicate(
5094    storage: &dyn StorageInterface,
5095    ids: &BTreeMap<String, EntityId>,
5096    pattern: &Pattern,
5097    params: &Params,
5098) -> Result<bool> {
5099    let Some(chain) = pattern.chains.first() else {
5100        return Ok(false);
5101    };
5102
5103    let start_id = write_pattern_node_binding(ids, pattern.start.variable.as_deref())?;
5104    let end_id = write_pattern_node_binding(ids, chain.node.variable.as_deref())?;
5105    let anchor_id = start_id.or(end_id).ok_or_else(|| {
5106        Error::Execution("pattern predicate is missing a bound endpoint".to_string())
5107    })?;
5108
5109    storage.check_query_control()?;
5110    let relationship_ids = match (start_id.is_some(), chain.relationship.direction) {
5111        (true, Direction::Outgoing) | (false, Direction::Incoming) => {
5112            storage.outgoing_relationships(anchor_id).to_vec()
5113        }
5114        (true, Direction::Incoming) | (false, Direction::Outgoing) => {
5115            storage.incoming_relationships(anchor_id).to_vec()
5116        }
5117        (_, Direction::Undirected) => storage
5118            .outgoing_relationships(anchor_id)
5119            .iter()
5120            .chain(storage.incoming_relationships(anchor_id))
5121            .copied()
5122            .collect::<Vec<_>>(),
5123    };
5124
5125    for (index, relationship_id) in relationship_ids.into_iter().enumerate() {
5126        if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
5127            storage.check_query_control()?;
5128        }
5129        let relationship = storage.relationship(relationship_id).ok_or_else(|| {
5130            Error::Execution(format!("relationship id {relationship_id} does not exist"))
5131        })?;
5132        if !write_relationship_matches(storage, ids, relationship, &chain.relationship, params)? {
5133            continue;
5134        }
5135        if let Some(variable) = &chain.relationship.variable {
5136            match ids.get(variable) {
5137                Some(EntityId::Relationship(bound_id)) if *bound_id == relationship_id => {}
5138                Some(EntityId::Relationship(_)) => continue,
5139                Some(EntityId::Node(_)) => return Ok(false),
5140                None => {
5141                    return Err(Error::Execution(format!(
5142                        "pattern predicate relationship variable `{variable}` is not bound"
5143                    )))
5144                }
5145            }
5146        }
5147
5148        let (candidate_start, candidate_end) = match chain.relationship.direction {
5149            Direction::Outgoing => (relationship.start, relationship.end),
5150            Direction::Incoming => (relationship.end, relationship.start),
5151            Direction::Undirected => {
5152                if start_id == Some(relationship.start) || end_id == Some(relationship.end) {
5153                    (relationship.start, relationship.end)
5154                } else {
5155                    (relationship.end, relationship.start)
5156                }
5157            }
5158        };
5159
5160        if start_id.is_some_and(|node_id| node_id != candidate_start)
5161            || end_id.is_some_and(|node_id| node_id != candidate_end)
5162        {
5163            continue;
5164        }
5165
5166        let start_node = storage
5167            .node(candidate_start)
5168            .ok_or_else(|| Error::Execution(format!("node id {candidate_start} does not exist")))?;
5169        let end_node = storage
5170            .node(candidate_end)
5171            .ok_or_else(|| Error::Execution(format!("node id {candidate_end} does not exist")))?;
5172        if write_node_matches(storage, ids, start_node, &pattern.start, params)?
5173            && write_node_matches(storage, ids, end_node, &chain.node, params)?
5174        {
5175            return Ok(true);
5176        }
5177    }
5178
5179    Ok(false)
5180}
5181
5182fn evaluate_write_exists_subquery(
5183    storage: &dyn StorageInterface,
5184    ids: &BTreeMap<String, EntityId>,
5185    matches: &[MatchClause],
5186    params: &Params,
5187) -> Result<bool> {
5188    for clause in matches {
5189        if clause.optional_match {
5190            return Err(Error::UnsupportedQueryFeature(
5191                "write expressions do not support OPTIONAL MATCH in EXISTS subqueries".to_string(),
5192            ));
5193        }
5194
5195        let mut patterns = Vec::with_capacity(1 + clause.patterns.len());
5196        patterns.push(&clause.pattern);
5197        patterns.extend(clause.patterns.iter());
5198        for pattern in patterns {
5199            if !evaluate_write_pattern_predicate(storage, ids, pattern, params)? {
5200                return Ok(false);
5201            }
5202        }
5203
5204        if let Some(predicate) = &clause.predicate {
5205            if !evaluate_write_predicate(storage, ids, predicate, params)? {
5206                return Ok(false);
5207            }
5208        }
5209    }
5210
5211    Ok(!matches.is_empty())
5212}
5213
5214fn write_pattern_node_binding(
5215    ids: &BTreeMap<String, EntityId>,
5216    variable: Option<&str>,
5217) -> Result<Option<NodeId>> {
5218    let Some(variable) = variable else {
5219        return Ok(None);
5220    };
5221
5222    match ids.get(variable) {
5223        Some(EntityId::Node(node_id)) => Ok(Some(*node_id)),
5224        Some(EntityId::Relationship(_)) => Ok(None),
5225        None => Err(Error::Validation(format!(
5226            "variable `{variable}` is not bound"
5227        ))),
5228    }
5229}
5230
5231fn write_optional_node_binding(
5232    ids: &BTreeMap<String, EntityId>,
5233    variable: Option<&str>,
5234) -> Result<Option<NodeId>> {
5235    let Some(variable) = variable else {
5236        return Ok(None);
5237    };
5238
5239    match ids.get(variable) {
5240        Some(EntityId::Node(node_id)) => Ok(Some(*node_id)),
5241        Some(EntityId::Relationship(_)) => Ok(None),
5242        None => Ok(None),
5243    }
5244}
5245
5246fn write_node_matches(
5247    storage: &dyn StorageInterface,
5248    ids: &BTreeMap<String, EntityId>,
5249    node: &crate::graph_model::Node,
5250    pattern: &NodePattern,
5251    params: &Params,
5252) -> Result<bool> {
5253    for label in &pattern.labels {
5254        if controlled_position(storage, &node.labels, |node_label| node_label == label)?.is_none() {
5255            return Ok(false);
5256        }
5257    }
5258
5259    write_properties_match(storage, ids, &node.properties, &pattern.properties, params)
5260}
5261
5262fn write_relationship_matches(
5263    storage: &dyn StorageInterface,
5264    ids: &BTreeMap<String, EntityId>,
5265    relationship: &crate::graph_model::Relationship,
5266    pattern: &RelationshipPattern,
5267    params: &Params,
5268) -> Result<bool> {
5269    if !pattern.types.is_empty()
5270        && controlled_position(storage, &pattern.types, |relationship_type| {
5271            relationship_type == &relationship.r#type
5272        })?
5273        .is_none()
5274    {
5275        return Ok(false);
5276    }
5277
5278    write_properties_match(
5279        storage,
5280        ids,
5281        &relationship.properties,
5282        &pattern.properties,
5283        params,
5284    )
5285}
5286
5287fn write_properties_match(
5288    storage: &dyn StorageInterface,
5289    ids: &BTreeMap<String, EntityId>,
5290    properties: &Properties,
5291    predicates: &[crate::cypher::ast::PropertyPredicate],
5292    params: &Params,
5293) -> Result<bool> {
5294    for predicate in predicates {
5295        let Some(actual) = properties.get(&predicate.key) else {
5296            return Ok(false);
5297        };
5298        let expected =
5299            evaluate_write_expression_with_entities(storage, ids, &predicate.expression, params)?;
5300        if actual != &expected {
5301            return Ok(false);
5302        }
5303    }
5304
5305    Ok(true)
5306}
5307
5308fn evaluate_write_operand(
5309    storage: &dyn StorageInterface,
5310    ids: &BTreeMap<String, EntityId>,
5311    operand: &Operand,
5312    params: &Params,
5313) -> Result<Value> {
5314    match operand {
5315        Operand::Literal(value) => Ok(value.clone()),
5316        Operand::Parameter(name) => params
5317            .get(name)
5318            .cloned()
5319            .ok_or_else(|| Error::Validation(format!("missing query parameter `{name}`"))),
5320        Operand::Property { variable, key } => entity_property_value(storage, ids, variable, key),
5321        Operand::DynamicProperty { variable, key } => {
5322            let key = evaluate_write_expression_with_entities(storage, ids, key, params)?;
5323            let Value::String(key) = key else {
5324                return Err(Error::Validation(
5325                    "dynamic property keys must evaluate to strings".to_string(),
5326                ));
5327            };
5328            entity_property_value(storage, ids, variable, &key)
5329        }
5330        Operand::Variable(variable) => match ids.get(variable) {
5331            Some(EntityId::Node(node_id)) => Ok(Value::String(
5332                storage
5333                    .node(*node_id)
5334                    .ok_or_else(|| Error::Execution(format!("node id {node_id} does not exist")))?
5335                    .external_id
5336                    .clone(),
5337            )),
5338            Some(EntityId::Relationship(relationship_id)) => Ok(Value::String(
5339                storage
5340                    .relationship(*relationship_id)
5341                    .ok_or_else(|| {
5342                        Error::Execution(format!(
5343                            "relationship id {relationship_id} does not exist"
5344                        ))
5345                    })?
5346                    .external_id
5347                    .clone(),
5348            )),
5349            None => Err(Error::Validation(format!(
5350                "variable `{variable}` is not bound"
5351            ))),
5352        },
5353    }
5354}
5355
5356fn entity_property_value(
5357    storage: &dyn StorageInterface,
5358    ids: &BTreeMap<String, EntityId>,
5359    variable: &str,
5360    key: &str,
5361) -> Result<Value> {
5362    match ids.get(variable) {
5363        Some(EntityId::Node(node_id)) => Ok(storage
5364            .node(*node_id)
5365            .ok_or_else(|| Error::Execution(format!("node id {node_id} does not exist")))?
5366            .properties
5367            .get(key)
5368            .cloned()
5369            .unwrap_or(Value::Null)),
5370        Some(EntityId::Relationship(relationship_id)) => Ok(storage
5371            .relationship(*relationship_id)
5372            .ok_or_else(|| {
5373                Error::Execution(format!("relationship id {relationship_id} does not exist"))
5374            })?
5375            .properties
5376            .get(key)
5377            .cloned()
5378            .unwrap_or(Value::Null)),
5379        None => Err(Error::Validation(format!(
5380            "variable `{variable}` is not bound"
5381        ))),
5382    }
5383}
5384
5385fn entity_properties(
5386    storage: &dyn StorageInterface,
5387    ids: &BTreeMap<String, EntityId>,
5388    variable: &str,
5389) -> Result<Properties> {
5390    match ids.get(variable) {
5391        Some(EntityId::Node(node_id)) => Ok(storage
5392            .node(*node_id)
5393            .ok_or_else(|| Error::Execution(format!("node id {node_id} does not exist")))?
5394            .properties
5395            .clone()),
5396        Some(EntityId::Relationship(relationship_id)) => Ok(storage
5397            .relationship(*relationship_id)
5398            .ok_or_else(|| {
5399                Error::Execution(format!("relationship id {relationship_id} does not exist"))
5400            })?
5401            .properties
5402            .clone()),
5403        None => Err(Error::Validation(format!(
5404            "variable `{variable}` is not bound"
5405        ))),
5406    }
5407}
5408
5409#[derive(Clone, Copy)]
5410enum WriteArithmeticOperator {
5411    Add,
5412    Subtract,
5413    Multiply,
5414    Divide,
5415    Modulo,
5416}
5417
5418#[derive(Clone, Copy)]
5419enum WriteStringCaseFunction {
5420    Lower,
5421    Upper,
5422}
5423
5424fn evaluate_write_string_case_value(
5425    value: Value,
5426    function: WriteStringCaseFunction,
5427) -> Result<Value> {
5428    match value {
5429        Value::String(value) => Ok(Value::String(match function {
5430            WriteStringCaseFunction::Lower => value.to_lowercase(),
5431            WriteStringCaseFunction::Upper => value.to_uppercase(),
5432        })),
5433        Value::Null => Ok(Value::Null),
5434        _ => Err(Error::Validation(
5435            "string case functions require string arguments".to_string(),
5436        )),
5437    }
5438}
5439
5440fn evaluate_write_to_string_value(value: Value) -> Result<Value> {
5441    match value {
5442        Value::String(value) => Ok(Value::String(value)),
5443        Value::Integer(value) => Ok(Value::String(value.to_string())),
5444        Value::Float(value) => Ok(Value::String(value.to_string())),
5445        Value::Boolean(value) => Ok(Value::String(value.to_string())),
5446        Value::Null => Ok(Value::Null),
5447        _ => Err(Error::Validation(
5448            "toString function requires a scalar argument".to_string(),
5449        )),
5450    }
5451}
5452
5453fn evaluate_write_to_integer_value(value: Value) -> Result<Value> {
5454    match value {
5455        Value::Integer(value) => Ok(Value::Integer(value)),
5456        Value::Float(value) => Ok(Value::Integer(value as i64)),
5457        Value::String(value) => Ok(value
5458            .parse::<i64>()
5459            .map(Value::Integer)
5460            .unwrap_or(Value::Null)),
5461        Value::Boolean(value) => Ok(Value::Integer(if value { 1 } else { 0 })),
5462        Value::Null => Ok(Value::Null),
5463        _ => Err(Error::Validation(
5464            "toInteger function requires a scalar argument".to_string(),
5465        )),
5466    }
5467}
5468
5469fn evaluate_write_to_float_value(value: Value) -> Result<Value> {
5470    match value {
5471        Value::Float(value) => Ok(Value::Float(value)),
5472        Value::Integer(value) => Ok(Value::Float(value as f64)),
5473        Value::String(value) => Ok(value
5474            .parse::<f64>()
5475            .map(Value::Float)
5476            .unwrap_or(Value::Null)),
5477        Value::Boolean(value) => Ok(Value::Float(if value { 1.0 } else { 0.0 })),
5478        Value::Null => Ok(Value::Null),
5479        _ => Err(Error::Validation(
5480            "toFloat function requires a scalar argument".to_string(),
5481        )),
5482    }
5483}
5484
5485fn evaluate_write_to_boolean_value(value: Value) -> Result<Value> {
5486    match value {
5487        Value::Boolean(value) => Ok(Value::Boolean(value)),
5488        Value::Integer(value) => Ok(Value::Boolean(value != 0)),
5489        Value::String(value) => match value.to_ascii_lowercase().as_str() {
5490            "true" => Ok(Value::Boolean(true)),
5491            "false" => Ok(Value::Boolean(false)),
5492            _ => Ok(Value::Null),
5493        },
5494        Value::Null => Ok(Value::Null),
5495        _ => Err(Error::Validation(
5496            "toBoolean function requires a scalar argument".to_string(),
5497        )),
5498    }
5499}
5500
5501fn evaluate_write_to_string_or_null_value(value: Value) -> Result<Value> {
5502    match evaluate_write_to_string_value(value) {
5503        Ok(value) => Ok(value),
5504        Err(Error::Validation(_)) => Ok(Value::Null),
5505        Err(error) => Err(error),
5506    }
5507}
5508
5509fn evaluate_write_to_integer_or_null_value(value: Value) -> Result<Value> {
5510    match evaluate_write_to_integer_value(value) {
5511        Ok(value) => Ok(value),
5512        Err(Error::Validation(_)) => Ok(Value::Null),
5513        Err(error) => Err(error),
5514    }
5515}
5516
5517fn evaluate_write_to_float_or_null_value(value: Value) -> Result<Value> {
5518    match evaluate_write_to_float_value(value) {
5519        Ok(value) => Ok(value),
5520        Err(Error::Validation(_)) => Ok(Value::Null),
5521        Err(error) => Err(error),
5522    }
5523}
5524
5525fn evaluate_write_to_boolean_or_null_value(value: Value) -> Result<Value> {
5526    match evaluate_write_to_boolean_value(value) {
5527        Ok(value) => Ok(value),
5528        Err(Error::Validation(_)) => Ok(Value::Null),
5529        Err(error) => Err(error),
5530    }
5531}
5532
5533fn evaluate_write_is_empty_value(value: Value) -> Result<Value> {
5534    match value {
5535        Value::String(value) => Ok(Value::Boolean(value.is_empty())),
5536        Value::List(values) => Ok(Value::Boolean(values.is_empty())),
5537        Value::Map(values) => Ok(Value::Boolean(values.is_empty())),
5538        Value::Null => Ok(Value::Null),
5539        _ => Err(Error::Validation(
5540            "isEmpty function requires string, list, or map arguments".to_string(),
5541        )),
5542    }
5543}
5544
5545fn evaluate_write_head_value(value: Value) -> Result<Value> {
5546    match value {
5547        Value::List(values) => Ok(values.into_iter().next().unwrap_or(Value::Null)),
5548        Value::Null => Ok(Value::Null),
5549        _ => Err(Error::Validation(
5550            "head function requires a list argument".to_string(),
5551        )),
5552    }
5553}
5554
5555fn evaluate_write_last_value(value: Value) -> Result<Value> {
5556    match value {
5557        Value::List(values) => Ok(values.into_iter().last().unwrap_or(Value::Null)),
5558        Value::Null => Ok(Value::Null),
5559        _ => Err(Error::Validation(
5560            "last function requires a list argument".to_string(),
5561        )),
5562    }
5563}
5564
5565fn evaluate_write_tail_value(value: Value) -> Result<Value> {
5566    match value {
5567        Value::List(values) => Ok(Value::List(values.into_iter().skip(1).collect())),
5568        Value::Null => Ok(Value::Null),
5569        _ => Err(Error::Validation(
5570            "tail function requires a list argument".to_string(),
5571        )),
5572    }
5573}
5574
5575fn evaluate_write_range_value(
5576    start: Value,
5577    end: Value,
5578    step: Option<Value>,
5579    storage: Option<&dyn StorageInterface>,
5580) -> Result<Value> {
5581    if matches!(start, Value::Null)
5582        || matches!(end, Value::Null)
5583        || step
5584            .as_ref()
5585            .is_some_and(|step| matches!(step, Value::Null))
5586    {
5587        return Ok(Value::Null);
5588    }
5589
5590    let Value::Integer(start) = start else {
5591        return Err(Error::Validation(
5592            "range function requires integer arguments".to_string(),
5593        ));
5594    };
5595    let Value::Integer(end) = end else {
5596        return Err(Error::Validation(
5597            "range function requires integer arguments".to_string(),
5598        ));
5599    };
5600    let step = match step {
5601        Some(Value::Integer(step)) => step,
5602        Some(_) => {
5603            return Err(Error::Validation(
5604                "range function requires integer arguments".to_string(),
5605            ))
5606        }
5607        None => 1,
5608    };
5609    if step == 0 {
5610        return Err(Error::Validation(
5611            "range function step cannot be zero".to_string(),
5612        ));
5613    }
5614
5615    let mut values = Vec::new();
5616    let mut current = start;
5617    if step > 0 {
5618        while current <= end {
5619            if values.len() % QUERY_CONTROL_COMPARISON_BATCH == 0 {
5620                if let Some(storage) = storage {
5621                    storage.check_query_control()?;
5622                }
5623            }
5624            values.push(Value::Integer(current));
5625            let Some(next) = current.checked_add(step) else {
5626                break;
5627            };
5628            current = next;
5629        }
5630    } else {
5631        while current >= end {
5632            if values.len() % QUERY_CONTROL_COMPARISON_BATCH == 0 {
5633                if let Some(storage) = storage {
5634                    storage.check_query_control()?;
5635                }
5636            }
5637            values.push(Value::Integer(current));
5638            let Some(next) = current.checked_add(step) else {
5639                break;
5640            };
5641            current = next;
5642        }
5643    }
5644
5645    Ok(Value::List(values))
5646}
5647
5648fn evaluate_write_list_index_value(value: Value, index: Value) -> Result<Value> {
5649    if matches!(value, Value::Null) || matches!(index, Value::Null) {
5650        return Ok(Value::Null);
5651    }
5652
5653    let Value::List(values) = value else {
5654        return Err(Error::Validation(
5655            "list index expression requires a list value".to_string(),
5656        ));
5657    };
5658    let Value::Integer(index) = index else {
5659        return Err(Error::Validation(
5660            "list index expression requires an integer index".to_string(),
5661        ));
5662    };
5663
5664    let index = if index < 0 {
5665        values.len() as i64 + index
5666    } else {
5667        index
5668    };
5669    if index < 0 {
5670        return Ok(Value::Null);
5671    }
5672
5673    Ok(values.get(index as usize).cloned().unwrap_or(Value::Null))
5674}
5675
5676fn evaluate_write_list_slice_value(
5677    value: Value,
5678    start: Option<Value>,
5679    end: Option<Value>,
5680) -> Result<Value> {
5681    if matches!(value, Value::Null)
5682        || start
5683            .as_ref()
5684            .is_some_and(|start| matches!(start, Value::Null))
5685        || end.as_ref().is_some_and(|end| matches!(end, Value::Null))
5686    {
5687        return Ok(Value::Null);
5688    }
5689
5690    let Value::List(values) = value else {
5691        return Err(Error::Validation(
5692            "list slice expression requires a list value".to_string(),
5693        ));
5694    };
5695    let start = match start {
5696        Some(Value::Integer(start)) => normalize_write_slice_bound(start, values.len()),
5697        Some(_) => {
5698            return Err(Error::Validation(
5699                "list slice expression requires integer bounds".to_string(),
5700            ))
5701        }
5702        None => 0,
5703    };
5704    let end = match end {
5705        Some(Value::Integer(end)) => normalize_write_slice_bound(end, values.len()),
5706        Some(_) => {
5707            return Err(Error::Validation(
5708                "list slice expression requires integer bounds".to_string(),
5709            ))
5710        }
5711        None => values.len(),
5712    };
5713
5714    if start >= end {
5715        return Ok(Value::List(Vec::new()));
5716    }
5717
5718    Ok(Value::List(values[start..end].to_vec()))
5719}
5720
5721fn normalize_write_slice_bound(bound: i64, len: usize) -> usize {
5722    let len = len as i64;
5723    let bound = if bound < 0 { len + bound } else { bound };
5724    bound.clamp(0, len) as usize
5725}
5726
5727fn evaluate_write_size_value(value: Value) -> Result<Value> {
5728    match value {
5729        Value::String(value) => Ok(Value::Integer(value.chars().count() as i64)),
5730        Value::List(values) => Ok(Value::Integer(values.len() as i64)),
5731        Value::Null => Ok(Value::Null),
5732        _ => Err(Error::Validation(
5733            "size function requires string or list arguments".to_string(),
5734        )),
5735    }
5736}
5737
5738fn evaluate_write_substring_value(
5739    value: Value,
5740    start: Value,
5741    length: Option<Value>,
5742) -> Result<Value> {
5743    if matches!(value, Value::Null)
5744        || matches!(start, Value::Null)
5745        || length
5746            .as_ref()
5747            .is_some_and(|length| matches!(length, Value::Null))
5748    {
5749        return Ok(Value::Null);
5750    }
5751
5752    let Value::String(value) = value else {
5753        return Err(Error::Validation(
5754            "substring function requires a string value".to_string(),
5755        ));
5756    };
5757    let Value::Integer(start) = start else {
5758        return Err(Error::Validation(
5759            "substring start must be an integer".to_string(),
5760        ));
5761    };
5762    if start < 0 {
5763        return Err(Error::Validation(
5764            "substring start must be non-negative".to_string(),
5765        ));
5766    }
5767    let length = match length {
5768        Some(Value::Integer(length)) if length >= 0 => Some(length as usize),
5769        Some(Value::Integer(_)) => {
5770            return Err(Error::Validation(
5771                "substring length must be non-negative".to_string(),
5772            ))
5773        }
5774        Some(_) => {
5775            return Err(Error::Validation(
5776                "substring length must be an integer".to_string(),
5777            ))
5778        }
5779        None => None,
5780    };
5781
5782    let chars = value.chars().skip(start as usize);
5783    let substring = match length {
5784        Some(length) => chars.take(length).collect(),
5785        None => chars.collect(),
5786    };
5787    Ok(Value::String(substring))
5788}
5789
5790fn evaluate_write_replace_value(value: Value, search: Value, replacement: Value) -> Result<Value> {
5791    if matches!(value, Value::Null)
5792        || matches!(search, Value::Null)
5793        || matches!(replacement, Value::Null)
5794    {
5795        return Ok(Value::Null);
5796    }
5797
5798    let Value::String(value) = value else {
5799        return Err(Error::Validation(
5800            "replace function requires a string value".to_string(),
5801        ));
5802    };
5803    let Value::String(search) = search else {
5804        return Err(Error::Validation(
5805            "replace search must be a string".to_string(),
5806        ));
5807    };
5808    let Value::String(replacement) = replacement else {
5809        return Err(Error::Validation(
5810            "replace replacement must be a string".to_string(),
5811        ));
5812    };
5813
5814    Ok(Value::String(value.replace(&search, &replacement)))
5815}
5816
5817fn evaluate_write_trim_value(value: Value, mode: &TrimMode) -> Result<Value> {
5818    match value {
5819        Value::String(value) => Ok(Value::String(match mode {
5820            TrimMode::Both => value.trim().to_string(),
5821            TrimMode::Left => value.trim_start().to_string(),
5822            TrimMode::Right => value.trim_end().to_string(),
5823        })),
5824        Value::Null => Ok(Value::Null),
5825        _ => Err(Error::Validation(
5826            "trim functions require string arguments".to_string(),
5827        )),
5828    }
5829}
5830
5831fn evaluate_write_split_value(value: Value, delimiter: Value) -> Result<Value> {
5832    if matches!(value, Value::Null) || matches!(delimiter, Value::Null) {
5833        return Ok(Value::Null);
5834    }
5835
5836    let Value::String(value) = value else {
5837        return Err(Error::Validation(
5838            "split function requires a string value".to_string(),
5839        ));
5840    };
5841    let Value::String(delimiter) = delimiter else {
5842        return Err(Error::Validation(
5843            "split delimiter must be a string".to_string(),
5844        ));
5845    };
5846
5847    Ok(Value::List(
5848        value
5849            .split(&delimiter)
5850            .map(|part| Value::String(part.to_string()))
5851            .collect(),
5852    ))
5853}
5854
5855fn evaluate_write_string_slice_value(
5856    value: Value,
5857    length: Value,
5858    mode: &StringSliceMode,
5859) -> Result<Value> {
5860    if matches!(value, Value::Null) || matches!(length, Value::Null) {
5861        return Ok(Value::Null);
5862    }
5863
5864    let Value::String(value) = value else {
5865        return Err(Error::Validation(
5866            "left and right functions require a string value".to_string(),
5867        ));
5868    };
5869    let Value::Integer(length) = length else {
5870        return Err(Error::Validation(
5871            "left and right length must be an integer".to_string(),
5872        ));
5873    };
5874    if length < 0 {
5875        return Err(Error::Validation(
5876            "left and right length must be non-negative".to_string(),
5877        ));
5878    }
5879
5880    let length = length as usize;
5881    let value = match mode {
5882        StringSliceMode::Left => value.chars().take(length).collect(),
5883        StringSliceMode::Right => {
5884            let chars = value.chars().collect::<Vec<_>>();
5885            chars
5886                .iter()
5887                .skip(chars.len().saturating_sub(length))
5888                .collect()
5889        }
5890    };
5891    Ok(Value::String(value))
5892}
5893
5894fn evaluate_write_reverse_value(value: Value) -> Result<Value> {
5895    match value {
5896        Value::String(value) => Ok(Value::String(value.chars().rev().collect())),
5897        Value::List(mut values) => {
5898            values.reverse();
5899            Ok(Value::List(values))
5900        }
5901        Value::Null => Ok(Value::Null),
5902        _ => Err(Error::Validation(
5903            "reverse function requires a string or list argument".to_string(),
5904        )),
5905    }
5906}
5907
5908fn evaluate_write_abs_value(value: Value) -> Result<Value> {
5909    match value {
5910        Value::Integer(value) => value
5911            .checked_abs()
5912            .map(Value::Integer)
5913            .ok_or_else(|| Error::Execution("integer abs result exceeds i64 range".to_string())),
5914        Value::Float(value) => Ok(Value::Float(value.abs())),
5915        Value::Null => Ok(Value::Null),
5916        _ => Err(Error::Validation(
5917            "abs function requires a numeric argument".to_string(),
5918        )),
5919    }
5920}
5921
5922fn evaluate_write_rounding_value(value: Value, mode: &RoundingMode) -> Result<Value> {
5923    match value {
5924        Value::Integer(value) => Ok(Value::Integer(value)),
5925        Value::Float(value) => Ok(Value::Float(match mode {
5926            RoundingMode::Ceil => value.ceil(),
5927            RoundingMode::Floor => value.floor(),
5928        })),
5929        Value::Null => Ok(Value::Null),
5930        _ => Err(Error::Validation(
5931            "ceil and floor functions require numeric arguments".to_string(),
5932        )),
5933    }
5934}
5935
5936fn evaluate_write_sign_value(value: Value) -> Result<Value> {
5937    match value {
5938        Value::Integer(value) => Ok(Value::Integer(value.signum())),
5939        Value::Float(value) => Ok(Value::Integer(if value > 0.0 {
5940            1
5941        } else if value < 0.0 {
5942            -1
5943        } else {
5944            0
5945        })),
5946        Value::Null => Ok(Value::Null),
5947        _ => Err(Error::Validation(
5948            "sign function requires a numeric argument".to_string(),
5949        )),
5950    }
5951}
5952
5953fn evaluate_write_sqrt_value(value: Value) -> Result<Value> {
5954    let value = match value {
5955        Value::Integer(value) => value as f64,
5956        Value::Float(value) => value,
5957        Value::Null => return Ok(Value::Null),
5958        _ => {
5959            return Err(Error::Validation(
5960                "sqrt function requires a numeric argument".to_string(),
5961            ))
5962        }
5963    };
5964
5965    if value < 0.0 {
5966        return Err(Error::Validation(
5967            "sqrt function requires a non-negative argument".to_string(),
5968        ));
5969    }
5970
5971    Ok(Value::Float(value.sqrt()))
5972}
5973
5974fn evaluate_write_round_value(value: Value) -> Result<Value> {
5975    match value {
5976        Value::Integer(value) => Ok(Value::Float(value as f64)),
5977        Value::Float(value) => Ok(Value::Float(value.round())),
5978        Value::Null => Ok(Value::Null),
5979        _ => Err(Error::Validation(
5980            "round function requires a numeric argument".to_string(),
5981        )),
5982    }
5983}
5984
5985fn evaluate_write_log_value(value: Value) -> Result<Value> {
5986    let value = match value {
5987        Value::Integer(value) => value as f64,
5988        Value::Float(value) => value,
5989        Value::Null => return Ok(Value::Null),
5990        _ => {
5991            return Err(Error::Validation(
5992                "log function requires a numeric argument".to_string(),
5993            ))
5994        }
5995    };
5996
5997    if value <= 0.0 {
5998        return Err(Error::Validation(
5999            "log function requires a positive argument".to_string(),
6000        ));
6001    }
6002
6003    Ok(Value::Float(value.ln()))
6004}
6005
6006fn evaluate_write_log10_value(value: Value) -> Result<Value> {
6007    let value = match value {
6008        Value::Integer(value) => value as f64,
6009        Value::Float(value) => value,
6010        Value::Null => return Ok(Value::Null),
6011        _ => {
6012            return Err(Error::Validation(
6013                "log10 function requires a numeric argument".to_string(),
6014            ))
6015        }
6016    };
6017
6018    if value <= 0.0 {
6019        return Err(Error::Validation(
6020            "log10 function requires a positive argument".to_string(),
6021        ));
6022    }
6023
6024    Ok(Value::Float(value.log10()))
6025}
6026
6027fn evaluate_write_exp_value(value: Value) -> Result<Value> {
6028    match value {
6029        Value::Integer(value) => Ok(Value::Float((value as f64).exp())),
6030        Value::Float(value) => Ok(Value::Float(value.exp())),
6031        Value::Null => Ok(Value::Null),
6032        _ => Err(Error::Validation(
6033            "exp function requires a numeric argument".to_string(),
6034        )),
6035    }
6036}
6037
6038fn evaluate_write_angle_conversion_value(
6039    value: Value,
6040    mode: &AngleConversionMode,
6041) -> Result<Value> {
6042    let value = match value {
6043        Value::Integer(value) => value as f64,
6044        Value::Float(value) => value,
6045        Value::Null => return Ok(Value::Null),
6046        _ => {
6047            return Err(Error::Validation(
6048                "degrees and radians functions require numeric arguments".to_string(),
6049            ))
6050        }
6051    };
6052
6053    Ok(Value::Float(match mode {
6054        AngleConversionMode::Degrees => value.to_degrees(),
6055        AngleConversionMode::Radians => value.to_radians(),
6056    }))
6057}
6058
6059fn evaluate_write_trigonometric_value(value: Value, mode: &TrigonometricMode) -> Result<Value> {
6060    let value = match value {
6061        Value::Integer(value) => value as f64,
6062        Value::Float(value) => value,
6063        Value::Null => return Ok(Value::Null),
6064        _ => {
6065            return Err(Error::Validation(
6066                "trigonometric functions require numeric arguments".to_string(),
6067            ))
6068        }
6069    };
6070
6071    Ok(Value::Float(match mode {
6072        TrigonometricMode::Sin => value.sin(),
6073        TrigonometricMode::Cos => value.cos(),
6074        TrigonometricMode::Tan => value.tan(),
6075        TrigonometricMode::Cot => 1.0 / value.tan(),
6076    }))
6077}
6078
6079fn evaluate_write_inverse_trigonometric_value(
6080    value: Value,
6081    mode: &InverseTrigonometricMode,
6082) -> Result<Value> {
6083    let value = match value {
6084        Value::Integer(value) => value as f64,
6085        Value::Float(value) => value,
6086        Value::Null => return Ok(Value::Null),
6087        _ => {
6088            return Err(Error::Validation(
6089                "inverse trigonometric functions require numeric arguments".to_string(),
6090            ))
6091        }
6092    };
6093
6094    Ok(Value::Float(match mode {
6095        InverseTrigonometricMode::Acos => value.acos(),
6096        InverseTrigonometricMode::Asin => value.asin(),
6097        InverseTrigonometricMode::Atan => value.atan(),
6098    }))
6099}
6100
6101fn evaluate_write_atan2_value(y: Value, x: Value) -> Result<Value> {
6102    if y == Value::Null || x == Value::Null {
6103        return Ok(Value::Null);
6104    }
6105
6106    let y = write_numeric_argument_value(y, "atan2")?;
6107    let x = write_numeric_argument_value(x, "atan2")?;
6108    Ok(Value::Float(y.atan2(x)))
6109}
6110
6111fn evaluate_write_haversin_value(value: Value) -> Result<Value> {
6112    let value = match value {
6113        Value::Integer(value) => value as f64,
6114        Value::Float(value) => value,
6115        Value::Null => return Ok(Value::Null),
6116        _ => {
6117            return Err(Error::Validation(
6118                "haversin function requires a numeric argument".to_string(),
6119            ))
6120        }
6121    };
6122
6123    let sine = (value / 2.0).sin();
6124    Ok(Value::Float(sine * sine))
6125}
6126
6127fn write_numeric_argument_value(value: Value, function: &str) -> Result<f64> {
6128    match value {
6129        Value::Integer(value) => Ok(value as f64),
6130        Value::Float(value) => Ok(value),
6131        _ => Err(Error::Validation(format!(
6132            "{function} function requires numeric arguments"
6133        ))),
6134    }
6135}
6136
6137fn evaluate_write_arithmetic_expression(
6138    left: &Expression,
6139    right: &Expression,
6140    operator: WriteArithmeticOperator,
6141    params: &Params,
6142) -> Result<Value> {
6143    let left = evaluate_write_expression(left, params)?;
6144    let right = evaluate_write_expression(right, params)?;
6145    evaluate_write_arithmetic_values(&left, &right, operator)
6146}
6147
6148fn evaluate_write_arithmetic_expression_with_entities(
6149    storage: &dyn StorageInterface,
6150    ids: &BTreeMap<String, EntityId>,
6151    left: &Expression,
6152    right: &Expression,
6153    operator: WriteArithmeticOperator,
6154    params: &Params,
6155) -> Result<Value> {
6156    let left = evaluate_write_expression_with_entities(storage, ids, left, params)?;
6157    let right = evaluate_write_expression_with_entities(storage, ids, right, params)?;
6158    evaluate_write_arithmetic_values(&left, &right, operator)
6159}
6160
6161fn compare_write_values(left: &Value, operator: ComparisonOperator, right: &Value) -> bool {
6162    match operator {
6163        ComparisonOperator::Equal => {
6164            left == right || numeric_write_ordering(left, right) == Some(Ordering::Equal)
6165        }
6166        ComparisonOperator::NotEqual => {
6167            left != right && numeric_write_ordering(left, right) != Some(Ordering::Equal)
6168        }
6169        ComparisonOperator::LessThan => {
6170            numeric_or_scalar_write_ordering(left, right) == Some(Ordering::Less)
6171        }
6172        ComparisonOperator::LessThanOrEqual => matches!(
6173            numeric_or_scalar_write_ordering(left, right),
6174            Some(Ordering::Less | Ordering::Equal)
6175        ),
6176        ComparisonOperator::GreaterThan => {
6177            numeric_or_scalar_write_ordering(left, right) == Some(Ordering::Greater)
6178        }
6179        ComparisonOperator::GreaterThanOrEqual => matches!(
6180            numeric_or_scalar_write_ordering(left, right),
6181            Some(Ordering::Greater | Ordering::Equal)
6182        ),
6183    }
6184}
6185
6186fn evaluate_write_in_predicate(
6187    list: Value,
6188    item: Value,
6189    storage: Option<&dyn StorageInterface>,
6190) -> Result<bool> {
6191    let Value::List(values) = list else {
6192        return Err(Error::Validation(
6193            "IN right-hand side must be a list".to_string(),
6194        ));
6195    };
6196
6197    for chunk in values.chunks(QUERY_CONTROL_COMPARISON_BATCH) {
6198        if let Some(storage) = storage {
6199            storage.check_query_control()?;
6200        }
6201        if chunk.iter().any(|value| {
6202            item == *value || numeric_write_ordering(&item, value) == Some(Ordering::Equal)
6203        }) {
6204            return Ok(true);
6205        }
6206    }
6207    Ok(false)
6208}
6209
6210fn evaluate_write_string_predicate(
6211    left: &Value,
6212    operator: StringOperator,
6213    right: &Value,
6214) -> Result<bool> {
6215    let (Value::String(left), Value::String(right)) = (left, right) else {
6216        return Ok(false);
6217    };
6218
6219    Ok(match operator {
6220        StringOperator::StartsWith => left.starts_with(right),
6221        StringOperator::EndsWith => left.ends_with(right),
6222        StringOperator::Contains => left.contains(right),
6223        StringOperator::Regex => Regex::new(right)
6224            .map_err(|error| Error::Validation(format!("invalid regex pattern: {error}")))?
6225            .is_match(left),
6226    })
6227}
6228
6229fn numeric_or_scalar_write_ordering(left: &Value, right: &Value) -> Option<Ordering> {
6230    numeric_write_ordering(left, right).or_else(|| match (left, right) {
6231        (Value::String(left), Value::String(right)) => Some(left.cmp(right)),
6232        (Value::Boolean(left), Value::Boolean(right)) => Some(left.cmp(right)),
6233        _ => None,
6234    })
6235}
6236
6237fn numeric_write_ordering(left: &Value, right: &Value) -> Option<Ordering> {
6238    match (left, right) {
6239        (Value::Integer(left), Value::Integer(right)) => Some(left.cmp(right)),
6240        (Value::Integer(left), Value::Float(right)) => (*left as f64).partial_cmp(right),
6241        (Value::Float(left), Value::Integer(right)) => left.partial_cmp(&(*right as f64)),
6242        (Value::Float(left), Value::Float(right)) => left.partial_cmp(right),
6243        _ => None,
6244    }
6245}
6246
6247fn evaluate_write_arithmetic_values(
6248    left: &Value,
6249    right: &Value,
6250    operator: WriteArithmeticOperator,
6251) -> Result<Value> {
6252    match (left, right, operator) {
6253        (Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::Add) => {
6254            left.checked_add(*right).map(Value::Integer).ok_or_else(|| {
6255                Error::Execution("integer addition result exceeds i64 range".to_string())
6256            })
6257        }
6258        (Value::String(left), Value::String(right), WriteArithmeticOperator::Add) => {
6259            Ok(Value::String(format!("{left}{right}")))
6260        }
6261        (Value::List(left), Value::List(right), WriteArithmeticOperator::Add) => {
6262            let mut values = left.clone();
6263            values.extend(right.clone());
6264            Ok(Value::List(values))
6265        }
6266        (Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::Subtract) => {
6267            left.checked_sub(*right).map(Value::Integer).ok_or_else(|| {
6268                Error::Execution("integer subtraction result exceeds i64 range".to_string())
6269            })
6270        }
6271        (Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::Multiply) => {
6272            left.checked_mul(*right).map(Value::Integer).ok_or_else(|| {
6273                Error::Execution("integer multiplication result exceeds i64 range".to_string())
6274            })
6275        }
6276        (Value::Integer(_), Value::Integer(0), WriteArithmeticOperator::Divide) => {
6277            Err(Error::Validation("division by zero".to_string()))
6278        }
6279        (Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::Divide) => {
6280            Ok(Value::Float(*left as f64 / *right as f64))
6281        }
6282        (Value::Integer(_), Value::Integer(0), WriteArithmeticOperator::Modulo) => {
6283            Err(Error::Validation("modulo by zero".to_string()))
6284        }
6285        (Value::Integer(left), Value::Integer(right), WriteArithmeticOperator::Modulo) => {
6286            Ok(Value::Integer(left % right))
6287        }
6288        (Value::Integer(left), Value::Float(right), operator) => {
6289            evaluate_write_float_arithmetic(*left as f64, *right, operator)
6290        }
6291        (Value::Float(left), Value::Integer(right), operator) => {
6292            evaluate_write_float_arithmetic(*left, *right as f64, operator)
6293        }
6294        (Value::Float(left), Value::Float(right), operator) => {
6295            evaluate_write_float_arithmetic(*left, *right, operator)
6296        }
6297        _ => Err(Error::Validation(
6298            "arithmetic operators require numeric operands".to_string(),
6299        )),
6300    }
6301}
6302
6303fn evaluate_write_float_arithmetic(
6304    left: f64,
6305    right: f64,
6306    operator: WriteArithmeticOperator,
6307) -> Result<Value> {
6308    match operator {
6309        WriteArithmeticOperator::Add => Ok(Value::Float(left + right)),
6310        WriteArithmeticOperator::Subtract => Ok(Value::Float(left - right)),
6311        WriteArithmeticOperator::Multiply => Ok(Value::Float(left * right)),
6312        WriteArithmeticOperator::Divide if right == 0.0 => {
6313            Err(Error::Validation("division by zero".to_string()))
6314        }
6315        WriteArithmeticOperator::Divide => Ok(Value::Float(left / right)),
6316        WriteArithmeticOperator::Modulo if right == 0.0 => {
6317            Err(Error::Validation("modulo by zero".to_string()))
6318        }
6319        WriteArithmeticOperator::Modulo => Ok(Value::Float(left % right)),
6320    }
6321}
6322
6323fn create_returns(
6324    returns: &ReturnProjection,
6325    created_variable: Option<&str>,
6326) -> Result<Vec<ReturnItem>> {
6327    match returns {
6328        ReturnProjection::Items(items) => Ok(items.clone()),
6329        ReturnProjection::Star => {
6330            let variable = created_variable.ok_or_else(|| {
6331                Error::Validation("CREATE RETURN * requires a node variable".to_string())
6332            })?;
6333            Ok(vec![ReturnItem {
6334                expression: ReturnExpression::Variable(variable.to_string()),
6335                alias: None,
6336            }])
6337        }
6338    }
6339}
6340
6341fn create_relationship_returns(
6342    returns: &ReturnProjection,
6343    path_variable: Option<&str>,
6344    relationship_variables: &[String],
6345) -> Result<Vec<ReturnItem>> {
6346    match returns {
6347        ReturnProjection::Items(items) => Ok(items.clone()),
6348        ReturnProjection::Star => {
6349            if path_variable.is_none() && relationship_variables.is_empty() {
6350                return Err(Error::Validation(
6351                    "CREATE relationship RETURN * requires a relationship variable".to_string(),
6352                ));
6353            }
6354
6355            let mut items = Vec::new();
6356            if let Some(variable) = path_variable {
6357                items.push(ReturnItem {
6358                    expression: ReturnExpression::Variable(variable.to_string()),
6359                    alias: None,
6360                });
6361            }
6362            items.extend(relationship_variables.iter().map(|variable| ReturnItem {
6363                expression: ReturnExpression::Variable(variable.clone()),
6364                alias: None,
6365            }));
6366            Ok(items)
6367        }
6368    }
6369}
6370
6371fn project_created_relationships_item(
6372    storage: &dyn StorageInterface,
6373    created: &CreatedRelationshipRow,
6374    item: &ReturnItem,
6375    params: &Params,
6376) -> Result<Value> {
6377    storage.check_query_control()?;
6378    match &item.expression {
6379        ReturnExpression::Variable(variable)
6380            if created
6381                .path
6382                .as_ref()
6383                .is_some_and(|path| path.variable == *variable) =>
6384        {
6385            created_path_value(
6386                storage,
6387                created.path.as_ref().expect("checked path variable"),
6388            )
6389        }
6390        ReturnExpression::Variable(variable)
6391        | ReturnExpression::Property { variable, .. }
6392        | ReturnExpression::Type(variable)
6393        | ReturnExpression::Properties(variable)
6394        | ReturnExpression::Keys(variable)
6395        | ReturnExpression::ElementId(variable) => {
6396            let relationship_id =
6397                created
6398                    .relationships
6399                    .get(variable)
6400                    .copied()
6401                    .ok_or_else(|| {
6402                        Error::Validation(
6403                            "CREATE relationship RETURN can only reference created relationships"
6404                                .to_string(),
6405                        )
6406                    })?;
6407            project_created_relationship_item(
6408                storage,
6409                relationship_id,
6410                Some(variable),
6411                item,
6412                params,
6413            )
6414        }
6415        ReturnExpression::Length(variable)
6416            if created
6417                .path
6418                .as_ref()
6419                .is_some_and(|path| path.variable == *variable) =>
6420        {
6421            Ok(Value::Integer(
6422                created
6423                    .path
6424                    .as_ref()
6425                    .expect("checked path variable")
6426                    .relationships
6427                    .len() as i64,
6428            ))
6429        }
6430        ReturnExpression::Nodes(variable)
6431            if created
6432                .path
6433                .as_ref()
6434                .is_some_and(|path| path.variable == *variable) =>
6435        {
6436            created_path_nodes_value(
6437                storage,
6438                created.path.as_ref().expect("checked path variable"),
6439            )
6440        }
6441        ReturnExpression::Relationships(variable)
6442            if created
6443                .path
6444                .as_ref()
6445                .is_some_and(|path| path.variable == *variable) =>
6446        {
6447            created_path_relationships_value(
6448                storage,
6449                created.path.as_ref().expect("checked path variable"),
6450            )
6451        }
6452        ReturnExpression::Scalar(expression) => {
6453            evaluate_create_return_expression(storage, expression, params)
6454        }
6455        ReturnExpression::Star => Err(Error::Execution(
6456            "CREATE relationship RETURN * should be expanded before projection".to_string(),
6457        )),
6458        _ => Err(Error::Validation(
6459            "CREATE relationship RETURN can only reference created relationships".to_string(),
6460        )),
6461    }
6462}
6463
6464fn created_path_value(storage: &dyn StorageInterface, path: &CreatedPath) -> Result<Value> {
6465    let Value::List(nodes) = created_path_nodes_value(storage, path)? else {
6466        unreachable!("created_path_nodes_value always returns Value::List")
6467    };
6468    let nodes = nodes
6469        .into_iter()
6470        .map(|value| {
6471            let Value::Node(node) = value else {
6472                unreachable!("created_path_nodes_value only returns node values")
6473            };
6474            node
6475        })
6476        .collect::<Vec<_>>();
6477    let Value::List(relationships) = created_path_relationships_value(storage, path)? else {
6478        unreachable!("created_path_relationships_value always returns Value::List")
6479    };
6480    let relationships = relationships
6481        .into_iter()
6482        .map(|value| {
6483            let Value::Relationship(relationship) = value else {
6484                unreachable!("created_path_relationships_value only returns relationship values")
6485            };
6486            relationship
6487        })
6488        .collect::<Vec<_>>();
6489
6490    Ok(Value::Path(crate::PathValue {
6491        nodes,
6492        relationships,
6493    }))
6494}
6495
6496fn created_path_nodes_value(storage: &dyn StorageInterface, path: &CreatedPath) -> Result<Value> {
6497    let mut nodes = Vec::with_capacity(path.nodes.len());
6498    for (index, node_id) in path.nodes.iter().enumerate() {
6499        if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
6500            storage.check_query_control()?;
6501        }
6502        let node = storage
6503            .node(*node_id)
6504            .ok_or_else(|| Error::Execution("created path node is missing".to_string()))?;
6505        nodes.push(Value::Node(crate::NodeValue::stored(
6506            *node_id as u64,
6507            node.external_id.clone(),
6508            node.labels.clone(),
6509            node.properties.clone(),
6510        )));
6511    }
6512    Ok(Value::List(nodes))
6513}
6514
6515fn created_path_relationships_value(
6516    storage: &dyn StorageInterface,
6517    path: &CreatedPath,
6518) -> Result<Value> {
6519    let mut relationships = Vec::with_capacity(path.relationships.len());
6520    for (index, relationship_id) in path.relationships.iter().enumerate() {
6521        if index % QUERY_CONTROL_COMPARISON_BATCH == 0 {
6522            storage.check_query_control()?;
6523        }
6524        relationships.push(Value::Relationship(relationship_value(
6525            storage,
6526            *relationship_id,
6527        )?));
6528    }
6529    Ok(Value::List(relationships))
6530}
6531
6532fn project_created_item(
6533    storage: &dyn StorageInterface,
6534    node_id: NodeId,
6535    created_variable: Option<&str>,
6536    item: &ReturnItem,
6537    params: &Params,
6538) -> Result<Value> {
6539    storage.check_query_control()?;
6540    match &item.expression {
6541        ReturnExpression::Variable(variable) if Some(variable.as_str()) == created_variable => {
6542            let node = storage
6543                .node(node_id)
6544                .ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
6545            Ok(Value::Node(crate::NodeValue::stored(
6546                node_id as u64,
6547                node.external_id.clone(),
6548                node.labels.clone(),
6549                node.properties.clone(),
6550            )))
6551        }
6552        ReturnExpression::Property { variable, key }
6553            if Some(variable.as_str()) == created_variable =>
6554        {
6555            let node = storage
6556                .node(node_id)
6557                .ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
6558            Ok(node.properties.get(key).cloned().unwrap_or(Value::Null))
6559        }
6560        ReturnExpression::Labels(variable) if Some(variable.as_str()) == created_variable => {
6561            let node = storage
6562                .node(node_id)
6563                .ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
6564            Ok(Value::List(
6565                node.labels.iter().cloned().map(Value::String).collect(),
6566            ))
6567        }
6568        ReturnExpression::Properties(variable) if Some(variable.as_str()) == created_variable => {
6569            let node = storage
6570                .node(node_id)
6571                .ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
6572            Ok(Value::Map(node.properties.clone()))
6573        }
6574        ReturnExpression::Keys(variable) if Some(variable.as_str()) == created_variable => {
6575            let node = storage
6576                .node(node_id)
6577                .ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
6578            Ok(Value::List(
6579                node.properties.keys().cloned().map(Value::String).collect(),
6580            ))
6581        }
6582        ReturnExpression::ElementId(variable) if Some(variable.as_str()) == created_variable => {
6583            let node = storage
6584                .node(node_id)
6585                .ok_or_else(|| Error::Execution("created node is missing".to_string()))?;
6586            Ok(Value::String(node.external_id.clone()))
6587        }
6588        ReturnExpression::Scalar(expression) => {
6589            if let Some(variable) = created_variable {
6590                let ids = BTreeMap::from([(variable.to_string(), EntityId::Node(node_id))]);
6591                evaluate_write_expression_with_entities(storage, &ids, expression, params)
6592            } else {
6593                evaluate_create_return_expression(storage, expression, params)
6594            }
6595        }
6596        ReturnExpression::Star => Err(Error::Execution(
6597            "CREATE RETURN * should be expanded before projection".to_string(),
6598        )),
6599        _ => Err(Error::Validation(
6600            "CREATE RETURN can only reference the created node".to_string(),
6601        )),
6602    }
6603}
6604
6605fn project_created_relationship_item(
6606    storage: &dyn StorageInterface,
6607    relationship_id: RelationshipId,
6608    created_variable: Option<&str>,
6609    item: &ReturnItem,
6610    params: &Params,
6611) -> Result<Value> {
6612    storage.check_query_control()?;
6613    let relationship = storage
6614        .relationship(relationship_id)
6615        .ok_or_else(|| Error::Execution("created relationship is missing".to_string()))?;
6616
6617    match &item.expression {
6618        ReturnExpression::Variable(variable) if Some(variable.as_str()) == created_variable => {
6619            let start = storage.node(relationship.start).ok_or_else(|| {
6620                Error::Execution("relationship start node is missing".to_string())
6621            })?;
6622            let end = storage
6623                .node(relationship.end)
6624                .ok_or_else(|| Error::Execution("relationship end node is missing".to_string()))?;
6625            Ok(Value::Relationship(crate::RelationshipValue::stored(
6626                relationship_id as u64,
6627                relationship.start as u64,
6628                relationship.end as u64,
6629                relationship.external_id.clone(),
6630                start.external_id.clone(),
6631                end.external_id.clone(),
6632                relationship.r#type.clone(),
6633                relationship.properties.clone(),
6634            )))
6635        }
6636        ReturnExpression::Property { variable, key }
6637            if Some(variable.as_str()) == created_variable =>
6638        {
6639            Ok(relationship
6640                .properties
6641                .get(key)
6642                .cloned()
6643                .unwrap_or(Value::Null))
6644        }
6645        ReturnExpression::Type(variable) if Some(variable.as_str()) == created_variable => {
6646            Ok(Value::String(relationship.r#type.clone()))
6647        }
6648        ReturnExpression::Properties(variable) if Some(variable.as_str()) == created_variable => {
6649            Ok(Value::Map(relationship.properties.clone()))
6650        }
6651        ReturnExpression::Keys(variable) if Some(variable.as_str()) == created_variable => {
6652            Ok(Value::List(
6653                relationship
6654                    .properties
6655                    .keys()
6656                    .cloned()
6657                    .map(Value::String)
6658                    .collect(),
6659            ))
6660        }
6661        ReturnExpression::ElementId(variable) if Some(variable.as_str()) == created_variable => {
6662            Ok(Value::String(relationship.external_id.clone()))
6663        }
6664        ReturnExpression::Scalar(expression) => {
6665            evaluate_create_return_expression(storage, expression, params)
6666        }
6667        ReturnExpression::Star => Err(Error::Execution(
6668            "CREATE relationship RETURN * should be expanded before projection".to_string(),
6669        )),
6670        _ => Err(Error::Validation(
6671            "CREATE relationship RETURN can only reference the created relationship".to_string(),
6672        )),
6673    }
6674}
6675
6676fn set_returns(
6677    returns: &ReturnProjection,
6678    target_variables: &BTreeSet<String>,
6679) -> Result<Vec<ReturnItem>> {
6680    match returns {
6681        ReturnProjection::Items(items) => Ok(items.clone()),
6682        ReturnProjection::Star => Ok(target_variables
6683            .iter()
6684            .map(|variable| ReturnItem {
6685                expression: ReturnExpression::Variable(variable.clone()),
6686                alias: None,
6687            })
6688            .collect()),
6689    }
6690}
6691
6692fn project_set_item(
6693    storage: &dyn StorageInterface,
6694    ids: &BTreeMap<String, EntityId>,
6695    item: &ReturnItem,
6696    params: &Params,
6697) -> Result<Value> {
6698    storage.check_query_control()?;
6699    match &item.expression {
6700        ReturnExpression::Variable(variable) => match set_entity_id(ids, variable)? {
6701            EntityId::Node(node_id) => {
6702                let node = storage
6703                    .node(node_id)
6704                    .ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
6705                Ok(Value::Node(crate::NodeValue::stored(
6706                    node_id as u64,
6707                    node.external_id.clone(),
6708                    node.labels.clone(),
6709                    node.properties.clone(),
6710                )))
6711            }
6712            EntityId::Relationship(relationship_id) => {
6713                relationship_value(storage, relationship_id).map(Value::Relationship)
6714            }
6715        },
6716        ReturnExpression::Property { variable, key } => match set_entity_id(ids, variable)? {
6717            EntityId::Node(node_id) => {
6718                let node = storage
6719                    .node(node_id)
6720                    .ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
6721                Ok(node.properties.get(key).cloned().unwrap_or(Value::Null))
6722            }
6723            EntityId::Relationship(relationship_id) => {
6724                let relationship = storage.relationship(relationship_id).ok_or_else(|| {
6725                    Error::Execution("updated relationship is missing".to_string())
6726                })?;
6727                Ok(relationship
6728                    .properties
6729                    .get(key)
6730                    .cloned()
6731                    .unwrap_or(Value::Null))
6732            }
6733        },
6734        ReturnExpression::Labels(variable) => {
6735            let EntityId::Node(node_id) = set_entity_id(ids, variable)? else {
6736                return Err(Error::Validation(
6737                    "labels() requires a node binding".to_string(),
6738                ));
6739            };
6740            let node = storage
6741                .node(node_id)
6742                .ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
6743            Ok(Value::List(
6744                node.labels.iter().cloned().map(Value::String).collect(),
6745            ))
6746        }
6747        ReturnExpression::Keys(variable) => {
6748            let properties = match set_entity_id(ids, variable)? {
6749                EntityId::Node(node_id) => {
6750                    let node = storage
6751                        .node(node_id)
6752                        .ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
6753                    &node.properties
6754                }
6755                EntityId::Relationship(relationship_id) => {
6756                    let relationship = storage.relationship(relationship_id).ok_or_else(|| {
6757                        Error::Execution("updated relationship is missing".to_string())
6758                    })?;
6759                    &relationship.properties
6760                }
6761            };
6762            Ok(Value::List(
6763                properties.keys().cloned().map(Value::String).collect(),
6764            ))
6765        }
6766        ReturnExpression::Properties(variable) => {
6767            let properties = match set_entity_id(ids, variable)? {
6768                EntityId::Node(node_id) => {
6769                    let node = storage
6770                        .node(node_id)
6771                        .ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
6772                    node.properties.clone()
6773                }
6774                EntityId::Relationship(relationship_id) => {
6775                    let relationship = storage.relationship(relationship_id).ok_or_else(|| {
6776                        Error::Execution("updated relationship is missing".to_string())
6777                    })?;
6778                    relationship.properties.clone()
6779                }
6780            };
6781            Ok(Value::Map(properties))
6782        }
6783        ReturnExpression::ElementId(variable) => {
6784            let external_id = match set_entity_id(ids, variable)? {
6785                EntityId::Node(node_id) => {
6786                    let node = storage
6787                        .node(node_id)
6788                        .ok_or_else(|| Error::Execution("updated node is missing".to_string()))?;
6789                    node.external_id.clone()
6790                }
6791                EntityId::Relationship(relationship_id) => {
6792                    let relationship = storage.relationship(relationship_id).ok_or_else(|| {
6793                        Error::Execution("updated relationship is missing".to_string())
6794                    })?;
6795                    relationship.external_id.clone()
6796                }
6797            };
6798            Ok(Value::String(external_id))
6799        }
6800        ReturnExpression::Type(variable) => {
6801            let EntityId::Relationship(relationship_id) = set_entity_id(ids, variable)? else {
6802                return Err(Error::Validation(
6803                    "type() requires a relationship binding".to_string(),
6804                ));
6805            };
6806            let relationship = storage
6807                .relationship(relationship_id)
6808                .ok_or_else(|| Error::Execution("updated relationship is missing".to_string()))?;
6809            Ok(Value::String(relationship.r#type.clone()))
6810        }
6811        ReturnExpression::Scalar(expression) => {
6812            evaluate_write_expression_with_entities(storage, ids, expression, params)
6813        }
6814        ReturnExpression::Star => Err(Error::Execution(
6815            "SET RETURN * should be expanded before projection".to_string(),
6816        )),
6817        _ => Err(Error::Validation(
6818            "SET RETURN currently supports updated node variables and properties".to_string(),
6819        )),
6820    }
6821}
6822
6823fn set_entity_id(ids: &BTreeMap<String, EntityId>, variable: &str) -> Result<EntityId> {
6824    ids.get(variable)
6825        .copied()
6826        .ok_or_else(|| Error::Validation(format!("SET RETURN variable `{variable}` is not bound")))
6827}
6828
6829fn relationship_value(
6830    storage: &dyn StorageInterface,
6831    relationship_id: RelationshipId,
6832) -> Result<crate::RelationshipValue> {
6833    let relationship = storage
6834        .relationship(relationship_id)
6835        .ok_or_else(|| Error::Execution("relationship is missing".to_string()))?;
6836    let start = storage
6837        .node(relationship.start)
6838        .ok_or_else(|| Error::Execution("relationship start node is missing".to_string()))?;
6839    let end = storage
6840        .node(relationship.end)
6841        .ok_or_else(|| Error::Execution("relationship end node is missing".to_string()))?;
6842    Ok(crate::RelationshipValue::stored(
6843        relationship_id as u64,
6844        relationship.start as u64,
6845        relationship.end as u64,
6846        relationship.external_id.clone(),
6847        start.external_id.clone(),
6848        end.external_id.clone(),
6849        relationship.r#type.clone(),
6850        relationship.properties.clone(),
6851    ))
6852}
6853
6854fn evaluate_create_return_expression(
6855    storage: &dyn StorageInterface,
6856    expression: &Expression,
6857    params: &Params,
6858) -> Result<Value> {
6859    evaluate_write_expression_with_entities(storage, &BTreeMap::new(), expression, params)
6860}
6861
6862fn create_return_column(item: &ReturnItem) -> String {
6863    item.alias
6864        .clone()
6865        .unwrap_or_else(|| match &item.expression {
6866            ReturnExpression::Variable(variable) => variable.clone(),
6867            ReturnExpression::Property { variable, key } => format!("{variable}.{key}"),
6868            ReturnExpression::Scalar(Expression::Literal(value))
6869            | ReturnExpression::Scalar(Expression::Operand(Operand::Literal(value))) => {
6870                format!("{value:?}")
6871            }
6872            _ => "expr".to_string(),
6873        })
6874}
6875
6876fn deduplicate_rows(storage: &dyn StorageInterface, rows: &mut Vec<Record>) -> Result<()> {
6877    let mut seen = Vec::<Record>::new();
6878    let mut distinct = Vec::with_capacity(rows.len());
6879    for row in rows.drain(..) {
6880        storage.check_query_control()?;
6881        if controlled_position(storage, &seen, |seen_row| seen_row == &row)?.is_none() {
6882            seen.push(row.clone());
6883            distinct.push(row);
6884        }
6885    }
6886    *rows = distinct;
6887    Ok(())
6888}
6889
6890fn query_from_matches(matches: Vec<MatchClause>, returns: ReturnProjection) -> Result<Query> {
6891    let first_match = matches
6892        .first()
6893        .cloned()
6894        .ok_or_else(|| Error::Parse("write statement is missing MATCH".to_string()))?;
6895    Ok(Query {
6896        has_initial_match: true,
6897        optional_match: first_match.optional_match,
6898        pattern: first_match.pattern.clone(),
6899        patterns: first_match.patterns,
6900        predicate: first_match.predicate,
6901        extra_matches: matches.into_iter().skip(1).collect(),
6902        unwinds: Vec::new(),
6903        post_unwind_matches: Vec::new(),
6904        procedure_calls: Vec::new(),
6905        post_procedure_unwinds: Vec::new(),
6906        post_procedure_matches: Vec::new(),
6907        with: None,
6908        with_predicate: None,
6909        with_order_by: Vec::new(),
6910        with_skip: None,
6911        with_limit: None,
6912        post_with_unwinds: Vec::new(),
6913        post_with_matches: Vec::new(),
6914        post_with_procedure_calls: Vec::new(),
6915        post_with_procedure_unwinds: Vec::new(),
6916        post_with_procedure_matches: Vec::new(),
6917        post_with_with: None,
6918        post_with_with_predicate: None,
6919        post_with_with_order_by: Vec::new(),
6920        post_with_with_skip: None,
6921        post_with_with_limit: None,
6922        post_with_with_unwinds: Vec::new(),
6923        post_with_with_matches: Vec::new(),
6924        post_with_with_procedure_calls: Vec::new(),
6925        post_with_with_procedure_unwinds: Vec::new(),
6926        post_with_with_procedure_matches: Vec::new(),
6927        post_with_with_calls: Vec::new(),
6928        calls: Vec::new(),
6929        post_call_unwinds: Vec::new(),
6930        post_call_matches: Vec::new(),
6931        post_call_with: None,
6932        post_call_with_predicate: None,
6933        post_call_with_order_by: Vec::new(),
6934        post_call_with_skip: None,
6935        post_call_with_limit: None,
6936        post_call_with_unwinds: Vec::new(),
6937        post_call_with_matches: Vec::new(),
6938        distinct: false,
6939        returns,
6940        implicit_return: false,
6941        order_by: Vec::new(),
6942        skip: None,
6943        limit: None,
6944    })
6945}