Skip to main content

uqa_engine/
graphs.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use super::{BTreeMap, Engine, RelationIdentity, StorageBackendResult, Value};
8use uqa_graph::GraphStore as _;
9
10mod catalog_oids;
11mod snapshots;
12
13fn graph_store_error(
14    error: impl std::error::Error + Send + Sync + 'static,
15) -> super::StorageBackendError {
16    super::StorageBackendError::backend("graph", error)
17}
18
19impl Engine {
20    pub fn create_graph(&self, name: impl Into<String>) -> StorageBackendResult<bool> {
21        let name = name.into();
22        self.with_implicit_graph_transaction(|engine| engine.create_graph_inner(&name))
23    }
24
25    fn create_graph_inner(&self, name: &str) -> StorageBackendResult<bool> {
26        use uqa_graph::GraphStore as _;
27        self.synchronize_catalog_registries()?;
28        let mut candidate = self
29            .graph_write_candidate(name, true)?
30            .expect("create candidate");
31        if candidate.has_graph(name).map_err(graph_store_error)? {
32            return Ok(false);
33        }
34        candidate.create_graph(name).map_err(graph_store_error)?;
35        let published = self.publish_graph_candidate(candidate)?;
36        self.durable
37            .graphs
38            .write()
39            .insert(name.to_string(), published);
40        self.note_catalog_registry_changed();
41        Ok(true)
42    }
43
44    /// Drop a named graph. No-op when the graph is missing.
45    pub fn drop_graph(&self, name: &str) -> StorageBackendResult<bool> {
46        self.with_implicit_graph_transaction(|engine| engine.drop_graph_inner(name))
47    }
48
49    fn drop_graph_inner(&self, name: &str) -> StorageBackendResult<bool> {
50        self.synchronize_catalog_registries()?;
51        let Some(mut store) = self.graph_write_candidate(name, false)? else {
52            return Ok(false);
53        };
54        let labels = store
55            .graph_labels(name)
56            .map_err(graph_store_error)?
57            .into_iter()
58            .map(|label| label.name)
59            .collect::<Vec<_>>();
60        uqa_execution::schema::deletion::drop_graph_label_dependents(
61            &uqa_execution::schema::deletion::CatalogRemovalInputs::catalog_removal_context(self),
62            name,
63            &labels,
64        )
65        .map_err(|error| super::StorageBackendError::Other(error.to_string()))?;
66        store.drop_graph(name).map_err(graph_store_error)?;
67        self.invalidate_graph_path_indexes(name)?;
68        self.publish_graph_candidate(store)?;
69        self.forget_graph_oids(name)?;
70        self.durable.graphs.write().remove(name);
71        self.durable
72            .path_indexes
73            .write()
74            .retain(|key, _| !key.starts_with(&format!("{name}::")));
75        self.note_catalog_registry_changed();
76        Ok(true)
77    }
78
79    /// Return every named graph registered on this engine in sorted order.
80    pub fn list_graphs(&self) -> StorageBackendResult<Vec<String>> {
81        self.with_direct_query_snapshot(true, Self::graph_names_in_execution, graph_store_error)
82    }
83
84    pub(crate) fn graph_names_in_execution(&self) -> StorageBackendResult<Vec<String>> {
85        self.synchronize_catalog_registries()?;
86        self.observe_graph_definition(
87            uqa_storage::catalog::graph_observations::GraphDefinitionKind::NamedGraph,
88            None,
89        )?;
90        Ok(self.visible_graph_handles().keys().cloned().collect())
91    }
92
93    /// Return `true` when a graph with `name` is registered.
94    pub fn has_graph(&self, name: &str) -> StorageBackendResult<bool> {
95        self.with_direct_query_snapshot(
96            true,
97            |engine| engine.has_graph_in_execution(name),
98            graph_store_error,
99        )
100    }
101
102    pub(crate) fn has_graph_in_execution(&self, name: &str) -> StorageBackendResult<bool> {
103        self.synchronize_catalog_registries()?;
104        Ok(self.graph_handle_in_execution(name)?.is_some())
105    }
106
107    /// Every named graph with its `ag_label` entries, read under one catalog
108    /// lock so catalog relations that mirror graphs do not re-read the
109    /// registry once per graph.
110    pub fn graph_label_catalog(
111        &self,
112    ) -> StorageBackendResult<Vec<(String, Vec<uqa_graph::GraphLabelInfo>)>> {
113        self.with_graph_read_snapshot(|engine| {
114            engine.observe_graph_definition(
115                uqa_storage::catalog::graph_observations::GraphDefinitionKind::NamedGraph,
116                None,
117            )?;
118            let context = engine.graph_read_context()?;
119            engine
120                .visible_graph_handles()
121                .iter()
122                .map(|(name, store)| {
123                    let labels = match (store.as_ref(), context.as_ref()) {
124                        (uqa_graph::GraphStoreHandle::Persistent(store), Some(context)) => store
125                            .with_serializable_read(context.clone(), &engine.runtime.cancellation)
126                            .graph_labels(name),
127                        _ => store.graph_labels(name),
128                    };
129                    labels
130                        .map(|labels| (name.clone(), labels))
131                        .map_err(graph_store_error)
132                })
133                .collect()
134        })
135    }
136
137    /// The surviving `ag_label` entries of a named graph in label-id order.
138    /// `None` when the graph does not exist.
139    pub fn list_graph_labels(
140        &self,
141        graph: &str,
142    ) -> StorageBackendResult<Option<Vec<uqa_graph::GraphLabelInfo>>> {
143        self.with_direct_query_snapshot(
144            true,
145            |engine| engine.graph_labels_in_execution(graph),
146            graph_store_error,
147        )
148    }
149
150    pub(crate) fn graph_labels_in_execution(
151        &self,
152        graph: &str,
153    ) -> StorageBackendResult<Option<Vec<uqa_graph::GraphLabelInfo>>> {
154        self.synchronize_catalog_registries()?;
155        let Some(store) = self.graph_handle_in_execution(graph)? else {
156            return Ok(None);
157        };
158        store
159            .graph_labels(graph)
160            .map(Some)
161            .map_err(graph_store_error)
162    }
163
164    /// Register an empty vertex or edge label in a named graph
165    /// (`create_vlabel` / `create_elabel`). Returns `false` when a label of
166    /// that name already exists in the graph and fails when the graph does
167    /// not exist.
168    pub fn create_graph_label(
169        &self,
170        graph: &str,
171        label: &str,
172        kind: uqa_graph::LabelKind,
173    ) -> StorageBackendResult<bool> {
174        self.with_implicit_graph_transaction(move |engine| {
175            engine.create_graph_label_inner(graph, label, kind)
176        })
177    }
178
179    fn create_graph_label_inner(
180        &self,
181        graph: &str,
182        label: &str,
183        kind: uqa_graph::LabelKind,
184    ) -> StorageBackendResult<bool> {
185        self.synchronize_catalog_registries()?;
186        let Some(mut candidate) = self.graph_write_candidate(graph, false)? else {
187            return Err(super::StorageBackendError::Other(format!(
188                "graph `{graph}` does not exist"
189            )));
190        };
191        let created = candidate
192            .create_label(graph, label, kind)
193            .map_err(graph_store_error)?
194            .is_some();
195        if !created {
196            return Ok(false);
197        }
198        let published = self.publish_graph_candidate(candidate)?;
199        self.durable
200            .graphs
201            .write()
202            .insert(graph.to_string(), published);
203        self.note_catalog_registry_changed();
204        Ok(true)
205    }
206
207    /// Drop a label and every entity carrying it from a named graph
208    /// (`drop_label`). Incident edge rows survive vertex-label removal like
209    /// AGE's `DROP TABLE`. Returns `false` when the label is not registered
210    /// and fails when the graph does not exist.
211    pub fn drop_graph_label(&self, graph: &str, label: &str) -> StorageBackendResult<bool> {
212        self.with_implicit_graph_transaction(move |engine| {
213            engine.drop_graph_label_inner(graph, label)
214        })
215    }
216
217    /// Stored views whose exact relation binding prevents a label relation from being dropped.
218    pub(crate) fn graph_label_relation_dependents(
219        &self,
220        graph: &str,
221        label: &str,
222    ) -> StorageBackendResult<Vec<String>> {
223        self.synchronize_catalog_registries()?;
224        let relation_name = format!(
225            "{}.{}",
226            uqa_sql::expr::quote_ident(graph),
227            uqa_sql::expr::quote_ident(label)
228        );
229        self.views_depending_on_relation(&relation_name)
230    }
231
232    fn drop_graph_label_inner(&self, graph: &str, label: &str) -> StorageBackendResult<bool> {
233        let dependent_views = self.graph_label_relation_dependents(graph, label)?;
234        if !dependent_views.is_empty() {
235            return Err(super::StorageBackendError::Other(format!(
236                "cannot drop label `{}.{}`: dependent view(s) `{}` still reference it",
237                uqa_sql::expr::quote_ident(graph),
238                uqa_sql::expr::quote_ident(label),
239                dependent_views.join("`, `")
240            )));
241        }
242        let Some(mut candidate) = self.graph_write_candidate(graph, false)? else {
243            return Err(super::StorageBackendError::Other(format!(
244                "graph `{graph}` does not exist"
245            )));
246        };
247        let Some((label_id, _)) = candidate
248            .drop_label(graph, label)
249            .map_err(graph_store_error)?
250        else {
251            return Ok(false);
252        };
253        self.invalidate_graph_path_indexes(graph)?;
254        let published = self.publish_graph_candidate(candidate)?;
255        self.forget_graph_label_oids(graph, &[label_id])?;
256        self.durable
257            .graphs
258            .write()
259            .insert(graph.to_string(), published);
260        self.note_catalog_registry_changed();
261        Ok(true)
262    }
263
264    /// Rename a named graph (`alter_graph(..., 'RENAME', ...)`). Returns
265    /// `false` when `from` does not exist and fails when `to` is already a
266    /// graph.
267    pub fn rename_graph(&self, from: &str, to: &str) -> StorageBackendResult<bool> {
268        self.with_implicit_graph_transaction(move |engine| engine.rename_graph_inner(from, to))
269    }
270
271    fn rename_graph_inner(&self, from: &str, to: &str) -> StorageBackendResult<bool> {
272        self.synchronize_catalog_registries()?;
273        let Some(mut candidate) = self.graph_write_candidate(from, false)? else {
274            return Ok(false);
275        };
276        if from == to {
277            return Ok(true);
278        }
279        if self.has_graph_in_execution(to)? {
280            return Err(super::StorageBackendError::Other(format!(
281                "graph `{to}` already exists"
282            )));
283        }
284        let labels = candidate.graph_labels(from).map_err(graph_store_error)?;
285        candidate
286            .rename_graph(from, to)
287            .map_err(graph_store_error)?;
288        let replacements = labels
289            .into_iter()
290            .map(|label| {
291                (
292                    RelationIdentity::new(from, &label.name),
293                    RelationIdentity::new(to, label.name),
294                )
295            })
296            .collect::<BTreeMap<_, _>>();
297        self.rewrite_view_relation_references(&replacements)?;
298        self.invalidate_graph_path_indexes(from)?;
299        self.rename_graph_oids(from, to)?;
300        let published = self.publish_graph_candidate(candidate)?;
301        let mut graphs = self.durable.graphs.write();
302        graphs.remove(from);
303        graphs.insert(to.to_string(), published);
304        drop(graphs);
305        self.note_catalog_registry_changed();
306        Ok(true)
307    }
308
309    /// Insert a vertex into a named graph, creating the graph if needed.
310    pub fn add_graph_vertex(
311        &self,
312        vertex: uqa_core::Vertex,
313        graph: &str,
314    ) -> StorageBackendResult<()> {
315        self.with_implicit_graph_transaction(move |engine| {
316            engine.add_graph_vertex_inner(vertex, graph)
317        })
318    }
319
320    fn add_graph_vertex_inner(
321        &self,
322        vertex: uqa_core::Vertex,
323        graph: &str,
324    ) -> StorageBackendResult<()> {
325        self.mutate_graph(graph, true, |store| store.add_vertex(vertex, graph))
326            .map(|_| ())
327    }
328
329    /// Insert an edge into a named graph, creating the graph if needed.
330    pub fn add_graph_edge(&self, edge: uqa_core::Edge, graph: &str) -> StorageBackendResult<()> {
331        self.with_implicit_graph_transaction(move |engine| engine.add_graph_edge_inner(edge, graph))
332    }
333
334    fn add_graph_edge_inner(&self, edge: uqa_core::Edge, graph: &str) -> StorageBackendResult<()> {
335        self.mutate_graph(graph, true, |store| store.add_edge(edge, graph))
336            .map(|_| ())
337    }
338
339    /// Apply a [`uqa_graph::GraphDelta`] to a named graph as one atomic batch
340    /// of vertex and edge additions or removals.
341    pub fn apply_graph_delta(
342        &self,
343        graph: &str,
344        delta: &uqa_graph::GraphDelta,
345    ) -> StorageBackendResult<()> {
346        self.with_implicit_graph_transaction(|engine| engine.apply_graph_delta_inner(graph, delta))
347    }
348
349    fn apply_graph_delta_inner(
350        &self,
351        graph: &str,
352        delta: &uqa_graph::GraphDelta,
353    ) -> StorageBackendResult<()> {
354        self.mutate_graph(graph, true, |store| {
355            for op in delta.ops() {
356                match op {
357                    uqa_graph::DeltaOp::AddVertex(vertex) => {
358                        store.add_vertex(vertex.clone(), graph)
359                    }
360                    uqa_graph::DeltaOp::RemoveVertex(id) => store.remove_vertex(*id, graph),
361                    uqa_graph::DeltaOp::AddEdge(edge) => store.add_edge(edge.clone(), graph),
362                    uqa_graph::DeltaOp::RemoveEdge(id) => store.remove_edge(*id, graph),
363                }?;
364            }
365            Ok(())
366        })
367        .map(|_| ())
368    }
369
370    /// Build (or replace) a path index for `graph` keyed by `name`.
371    /// `label_sequences` is the set of label sequences to materialize; each
372    /// sequence becomes a hash-friendly direct lookup for RPQ.
373    pub fn build_path_index(
374        &self,
375        name: &str,
376        graph: &str,
377        label_sequences: &[Vec<String>],
378    ) -> StorageBackendResult<bool> {
379        self.with_implicit_graph_transaction(|engine| {
380            engine.build_path_index_inner(name, graph, label_sequences)
381        })
382    }
383
384    fn build_path_index_inner(
385        &self,
386        name: &str,
387        graph: &str,
388        label_sequences: &[Vec<String>],
389    ) -> StorageBackendResult<bool> {
390        self.synchronize_catalog_registries()?;
391        self.observe_graph_definition(
392            uqa_storage::catalog::graph_observations::GraphDefinitionKind::NamedGraph,
393            Some(graph),
394        )?;
395        let key = format!("{graph}::{name}");
396        let idx = {
397            let graphs = self.durable.graphs.read();
398            let Some(store) = graphs.get(graph) else {
399                return Ok(false);
400            };
401            match (&self.storage.catalog, &self.storage.backend) {
402                (Some(catalog), Some(backend)) => uqa_graph::PathIndex::build_persistent(
403                    std::sync::Arc::clone(catalog),
404                    std::sync::Arc::clone(backend),
405                    &key,
406                    graph,
407                    label_sequences,
408                ),
409                (None, None) => uqa_graph::PathIndex::build(store.as_ref(), graph, label_sequences),
410                _ => {
411                    return Err(super::StorageBackendError::Other(
412                        "path-index catalog and backend must share a storage session".into(),
413                    ))
414                }
415            }
416            .map_err(graph_store_error)?
417        };
418        self.durable.path_indexes.write().insert(key, idx);
419        self.note_catalog_registry_changed();
420        Ok(true)
421    }
422
423    /// Drop a path index by `(graph, name)`. Return `true` when one existed.
424    pub fn drop_path_index(&self, name: &str, graph: &str) -> StorageBackendResult<bool> {
425        self.with_implicit_graph_transaction(|engine| engine.drop_path_index_inner(name, graph))
426    }
427
428    fn drop_path_index_inner(&self, name: &str, graph: &str) -> StorageBackendResult<bool> {
429        self.synchronize_catalog_registries()?;
430        let key = format!("{graph}::{name}");
431        self.observe_graph_definition(
432            uqa_storage::catalog::graph_observations::GraphDefinitionKind::PathIndex,
433            Some(&key),
434        )?;
435        if !self.durable.path_indexes.read().contains_key(&key) {
436            return Ok(false);
437        }
438        if let Some(catalog) = self.storage.catalog.as_ref() {
439            catalog.drop_path_index(&key)?;
440        }
441        let removed = self.durable.path_indexes.write().remove(&key).is_some();
442        if removed {
443            self.note_catalog_registry_changed();
444        }
445        Ok(removed)
446    }
447
448    /// Look up a path index by `(graph, name)`. Return a clone so the caller
449    /// is not tied to the engine's lock.
450    pub fn get_path_index(
451        &self,
452        name: &str,
453        graph: &str,
454    ) -> StorageBackendResult<Option<uqa_graph::PathIndex>> {
455        self.with_graph_read_snapshot(|engine| engine.path_index_in_execution(name, graph))
456    }
457
458    fn path_index_in_execution(
459        &self,
460        name: &str,
461        graph: &str,
462    ) -> StorageBackendResult<Option<uqa_graph::PathIndex>> {
463        let key = format!("{graph}::{name}");
464        self.observe_graph_definition(
465            uqa_storage::catalog::graph_observations::GraphDefinitionKind::PathIndex,
466            Some(&key),
467        )?;
468        let index = self.query_catalog_snapshot.as_ref().map_or_else(
469            || self.durable.path_indexes.read().get(&key).cloned(),
470            |snapshot| snapshot.path_indexes.get(&key).cloned(),
471        );
472        if self.query_catalog_snapshot.is_some()
473            || self.session.state.read().graph_overlay.is_some()
474        {
475            return Ok(match index {
476                Some(index) => self
477                    .graph_handle_in_execution(graph)?
478                    .map(|store| index.with_graph_read_view(store)),
479                None => None,
480            });
481        }
482        Ok(index)
483    }
484
485    /// Sorted list of registered path index keys. Each key has the
486    /// shape `<graph>::<name>` so the caller can split as needed.
487    pub fn list_path_indexes(&self) -> StorageBackendResult<Vec<String>> {
488        self.with_graph_read_snapshot(|engine| {
489            engine.observe_graph_definition(
490                uqa_storage::catalog::graph_observations::GraphDefinitionKind::PathIndex,
491                None,
492            )?;
493            Ok(engine.query_catalog_snapshot.as_ref().map_or_else(
494                || engine.durable.path_indexes.read().keys().cloned().collect(),
495                |snapshot| snapshot.path_indexes.keys().cloned().collect(),
496            ))
497        })
498    }
499
500    /// Read-only borrow of a named graph for ad-hoc query construction
501    /// outside the SQL function path. Returns `None` when the graph
502    /// is unknown.
503    pub fn graph_with<R>(
504        &self,
505        name: &str,
506        f: impl FnOnce(&uqa_graph::GraphStoreHandle) -> R,
507    ) -> StorageBackendResult<Option<R>> {
508        self.graph_handle_with(name, |store| f(store.as_ref()))
509    }
510
511    pub(crate) fn graph_handle_with<R>(
512        &self,
513        name: &str,
514        f: impl FnOnce(&std::sync::Arc<uqa_graph::GraphStoreHandle>) -> R,
515    ) -> StorageBackendResult<Option<R>> {
516        self.with_graph_read_snapshot(|engine| {
517            Ok(engine.graph_handle_in_execution(name)?.as_ref().map(f))
518        })
519    }
520
521    /// The enclosing query owns the statement gate and physical snapshot.
522    /// Parallel operators share that snapshot instead of reacquiring the
523    /// coordinator's thread-affine statement gate from a worker thread.
524    pub(crate) fn graph_handle_in_execution(
525        &self,
526        name: &str,
527    ) -> StorageBackendResult<Option<std::sync::Arc<uqa_graph::GraphStoreHandle>>> {
528        self.observe_graph_definition(
529            uqa_storage::catalog::graph_observations::GraphDefinitionKind::NamedGraph,
530            Some(name),
531        )?;
532        self.selected_graph_handle(name)
533    }
534
535    pub(crate) fn graph_statistics_with<R>(
536        &self,
537        name: &str,
538        f: impl FnOnce(&uqa_graph::GraphStoreHandle) -> R,
539    ) -> StorageBackendResult<Option<R>> {
540        self.with_graph_read_snapshot(|engine| {
541            Ok(engine
542                .selected_graph_handle(name)?
543                .map(|store| f(&store.for_statistics())))
544        })
545    }
546
547    fn observe_graph_definition(
548        &self,
549        kind: uqa_storage::catalog::graph_observations::GraphDefinitionKind,
550        name: Option<&str>,
551    ) -> StorageBackendResult<()> {
552        if let Some(context) = self.graph_read_context()? {
553            self.new_graph_store()?
554                .with_serializable_read(context, &self.runtime.cancellation)
555                .observe_definition(kind, name)
556                .map_err(graph_store_error)?;
557        }
558        Ok(())
559    }
560
561    fn selected_graph_handle(
562        &self,
563        name: &str,
564    ) -> StorageBackendResult<Option<std::sync::Arc<uqa_graph::GraphStoreHandle>>> {
565        let store = if let Some(snapshot) = &self.query_catalog_snapshot {
566            snapshot.graphs.get(name).cloned()
567        } else if let Some(overlay) = &self.session.state.read().graph_overlay {
568            overlay.names.contains(name).then(|| {
569                std::sync::Arc::new(uqa_graph::GraphStoreHandle::Persistent(
570                    overlay.store.as_ref().clone(),
571                ))
572            })
573        } else {
574            self.durable.graphs.read().get(name).cloned()
575        };
576        let Some(context) = self.graph_read_context()? else {
577            return Ok(store);
578        };
579        Ok(store.map(|store| {
580            std::sync::Arc::new(
581                store
582                    .as_ref()
583                    .clone()
584                    .with_serializable_read(context, &self.runtime.cancellation),
585            )
586        }))
587    }
588
589    pub(super) fn bind_graph_reader(
590        &self,
591        store: uqa_graph::GraphStoreHandle,
592    ) -> StorageBackendResult<uqa_graph::GraphStoreHandle> {
593        match self.graph_read_context()? {
594            None => Ok(store),
595            Some(context) => Ok(store.with_serializable_read(context, &self.runtime.cancellation)),
596        }
597    }
598
599    pub(crate) fn graph_read_context(
600        &self,
601    ) -> StorageBackendResult<Option<uqa_storage::mvcc::SerializableReadContext>> {
602        Ok(self
603            .storage
604            .backend
605            .as_ref()
606            .and_then(|backend| backend.serializable_session())
607            .map(uqa_storage::mvcc::SerializableSession::serializable_read_context)
608            .transpose()?
609            .flatten())
610    }
611
612    pub(crate) fn with_graph_read_snapshot<R>(
613        &self,
614        f: impl FnOnce(&Self) -> StorageBackendResult<R>,
615    ) -> StorageBackendResult<R> {
616        self.with_direct_query_snapshot(
617            true,
618            |engine| {
619                engine.synchronize_catalog_registries()?;
620                f(engine)
621            },
622            graph_store_error,
623        )
624    }
625
626    /// Mutable borrow of a named graph for vertex / edge insertion.
627    pub fn graph_with_mut<R>(
628        &self,
629        name: &str,
630        f: impl FnOnce(&mut uqa_graph::GraphStoreHandle) -> uqa_graph::GraphStoreResult<R>,
631    ) -> StorageBackendResult<Option<R>> {
632        self.with_implicit_graph_transaction(move |engine| engine.graph_with_mut_inner(name, f))
633    }
634
635    fn graph_with_mut_inner<R>(
636        &self,
637        name: &str,
638        f: impl FnOnce(&mut uqa_graph::GraphStoreHandle) -> uqa_graph::GraphStoreResult<R>,
639    ) -> StorageBackendResult<Option<R>> {
640        self.mutate_graph(name, false, f)
641    }
642
643    fn mutate_graph<R>(
644        &self,
645        name: &str,
646        create: bool,
647        f: impl FnOnce(&mut uqa_graph::GraphStoreHandle) -> uqa_graph::GraphStoreResult<R>,
648    ) -> StorageBackendResult<Option<R>> {
649        self.synchronize_catalog_registries()?;
650        let Some(mut candidate) = self.graph_write_candidate(name, create)? else {
651            return Ok(None);
652        };
653        let result = candidate
654            .transaction(|store| {
655                if !store.has_graph(name)? {
656                    store.create_graph(name)?;
657                }
658                let result = f(store)?;
659                self.invalidate_graph_path_indexes(name)?;
660                Ok(result)
661            })
662            .map_err(graph_store_error)?;
663        let published = self.publish_graph_candidate(candidate)?;
664        self.durable
665            .graphs
666            .write()
667            .insert(name.to_owned(), published);
668        self.note_catalog_registry_changed();
669        Ok(Some(result))
670    }
671
672    /// Run a Cypher query against a named graph and return the
673    /// `(columns, rows)` projected by the query's `RETURN` clause (or
674    /// empty vectors when the query has no `RETURN`).
675    ///
676    /// This wires the full `CREATE` / `MERGE` / `SET` / `DELETE` /
677    /// `UNWIND` surface through to the selected storage backend. The named graph is
678    /// auto-created on first use.
679    pub fn run_cypher(
680        &self,
681        graph: &str,
682        query: &str,
683        params: BTreeMap<String, Value>,
684    ) -> Result<(Vec<String>, Vec<uqa_graph::cypher::ResultRow>), uqa_graph::cypher::CypherError>
685    {
686        use uqa_graph::cypher::{CypherError, CypherExecutor};
687        // Even a read query can create its named graph on first use.
688        self.with_direct_query_snapshot(
689            false,
690            |engine| {
691                let query = uqa_graph::cypher::parse_cypher(query)?;
692                let existed = engine
693                    .has_graph_in_execution(graph)
694                    .map_err(CypherError::from)?;
695                if query.mutates_graph() || !existed {
696                    return engine.with_implicit_mapped_transaction(
697                        |engine| engine.run_cypher_inner(graph, &query, params),
698                        |error| CypherError::from(graph_store_error(error)),
699                    );
700                }
701                let store = engine
702                    .graph_handle_in_execution(graph)
703                    .map_err(CypherError::from)?
704                    .ok_or_else(|| {
705                        CypherError::Storage(format!("graph {graph:?} does not exist"))
706                    })?;
707                uqa_graph::cypher::validate_default_label_relations(store.as_ref(), graph, &query)?;
708                CypherExecutor::new(store.as_ref(), graph)
709                    .with_params(params)
710                    .execute(&query)
711            },
712            |error| CypherError::from(graph_store_error(error)),
713        )
714    }
715
716    fn run_cypher_inner(
717        &self,
718        graph: &str,
719        query: &uqa_graph::cypher::CypherQuery,
720        params: BTreeMap<String, Value>,
721    ) -> Result<(Vec<String>, Vec<uqa_graph::cypher::ResultRow>), uqa_graph::cypher::CypherError>
722    {
723        use uqa_graph::cypher::{CypherError, CypherWriter};
724        self.synchronize_catalog_registries()
725            .map_err(CypherError::from)?;
726        let mut candidate = self
727            .graph_write_candidate(graph, true)
728            .map_err(CypherError::from)?
729            .expect("create candidate");
730        let result = candidate.transaction_mapped(
731            |store| {
732                if !store.has_graph(graph).map_err(CypherError::from)? {
733                    store.create_graph(graph).map_err(CypherError::from)?;
734                }
735                uqa_graph::cypher::validate_default_label_relations(store, graph, query)?;
736                let result = CypherWriter::new(store, graph)
737                    .with_params(params)
738                    .execute(query)?;
739                self.invalidate_graph_path_indexes(graph)
740                    .map_err(CypherError::from)?;
741                Ok(result)
742            },
743            CypherError::from,
744        )?;
745        let published = self
746            .publish_graph_candidate(candidate)
747            .map_err(CypherError::from)?;
748        self.durable
749            .graphs
750            .write()
751            .insert(graph.to_owned(), published);
752        self.note_catalog_registry_changed();
753        Ok(result)
754    }
755
756    fn invalidate_graph_path_indexes(&self, graph: &str) -> StorageBackendResult<()> {
757        if let Some(catalog) = &self.storage.catalog {
758            for (key, _) in catalog.load_path_indexes()? {
759                if key.starts_with(&format!("{graph}::")) {
760                    catalog.drop_path_index(&key)?;
761                }
762            }
763        }
764        self.durable
765            .path_indexes
766            .write()
767            .retain(|key, _| !key.starts_with(&format!("{graph}::")));
768        Ok(())
769    }
770}