Skip to main content

uqa_graph/
handle.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Graph runtime selection: memory is primary storage only for an in-memory
8//! engine; durable engines retain only session-bound storage handles.
9
10use crate::{
11    Direction, GraphLabelInfo, GraphLabelRegistry, GraphStore, GraphStoreResult, LabelKind,
12    MemoryGraphStore, PersistentGraphStore,
13};
14use std::collections::{BTreeMap, BTreeSet};
15use std::sync::Arc;
16use uqa_core::{Edge, Vertex};
17use uqa_storage::{CatalogFacade, PersistentStorageBackend};
18
19#[derive(Debug, Clone)]
20pub enum GraphStoreHandle {
21    Memory(MemoryGraphStore),
22    Persistent(PersistentGraphStore),
23}
24
25impl Default for GraphStoreHandle {
26    fn default() -> Self {
27        Self::Memory(MemoryGraphStore::new())
28    }
29}
30
31impl GraphStoreHandle {
32    /// Record a semantic definition read from a retained catalog cache without loading graph data.
33    pub fn observe_definition(
34        &self,
35        kind: uqa_storage::catalog::graph_observations::GraphDefinitionKind,
36        name: Option<&str>,
37    ) -> GraphStoreResult<()> {
38        match self {
39            Self::Memory(_) => Ok(()),
40            Self::Persistent(store) => store.observe_definition(kind, name),
41        }
42    }
43
44    pub fn with_serializable_read(
45        self,
46        context: uqa_storage::mvcc::SerializableReadContext,
47        cancellation: &uqa_core::CancellationToken,
48    ) -> Self {
49        match self {
50            Self::Memory(_) => self,
51            Self::Persistent(store) => {
52                Self::Persistent(store.with_serializable_read(context, cancellation))
53            }
54        }
55    }
56
57    pub fn without_serializable_read(self) -> Self {
58        match self {
59            Self::Memory(_) => self,
60            Self::Persistent(store) => Self::Persistent(store.without_serializable_read()),
61        }
62    }
63
64    /// Cost estimation retains the same data without creating semantic query reads. The primary in-memory graph remains borrowed; persistent handles share their original storage and retained resources.
65    pub fn for_statistics(&self) -> std::borrow::Cow<'_, Self> {
66        match self {
67            Self::Memory(_) => std::borrow::Cow::Borrowed(self),
68            Self::Persistent(store) => {
69                std::borrow::Cow::Owned(Self::Persistent(store.clone().without_serializable_read()))
70            }
71        }
72    }
73    pub fn from_catalog(
74        catalog: Arc<dyn CatalogFacade>,
75        backend: Arc<dyn PersistentStorageBackend>,
76    ) -> Self {
77        Self::Persistent(PersistentGraphStore::from_catalog(catalog, backend))
78    }
79
80    /// Preserve caller error types while storage checkpoints (or the primary
81    /// memory store) roll back the complete operation on errors and panics.
82    pub fn transaction_mapped<T, E>(
83        &mut self,
84        operation: impl FnOnce(&mut Self) -> Result<T, E>,
85        map_error: impl Fn(crate::GraphStoreError) -> E,
86    ) -> Result<T, E>
87    where
88        E: std::fmt::Display,
89    {
90        match self {
91            Self::Memory(store) => {
92                let backup = store.clone();
93                match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| operation(self))) {
94                    Ok(Ok(value)) => Ok(value),
95                    Ok(Err(error)) => {
96                        *self = Self::Memory(backup);
97                        Err(error)
98                    }
99                    Err(panic) => {
100                        *self = Self::Memory(backup);
101                        std::panic::resume_unwind(panic)
102                    }
103                }
104            }
105            Self::Persistent(store) => {
106                let mut checkpoint = store.clone();
107                checkpoint.transaction_mapped(|_| operation(self), map_error)
108            }
109        }
110    }
111
112    pub fn label_registry(&self, graph: &str) -> GraphStoreResult<GraphLabelRegistry> {
113        match self {
114            Self::Memory(store) => Ok(store.label_registry(graph)),
115            Self::Persistent(store) => store.label_registry(graph),
116        }
117    }
118    pub fn graph_labels(&self, graph: &str) -> GraphStoreResult<Vec<GraphLabelInfo>> {
119        match self {
120            Self::Memory(store) => store.graph_labels(graph),
121            Self::Persistent(store) => store.graph_labels(graph),
122        }
123    }
124
125    /// Cypher validates the registry even for constant expressions, but only required default relations contribute semantic label dependencies.
126    pub(crate) fn default_label_relations(
127        &self,
128        graph: &str,
129        required: [bool; 2],
130    ) -> GraphStoreResult<[bool; 2]> {
131        let kinds = [crate::LabelKind::Vertex, crate::LabelKind::Edge];
132        let labels = match self {
133            Self::Memory(store) => store.graph_labels(graph)?,
134            Self::Persistent(store) => {
135                store.observe_definition(
136                    uqa_storage::catalog::graph_observations::GraphDefinitionKind::NamedGraph,
137                    Some(graph),
138                )?;
139                for (required, kind) in required.into_iter().zip(kinds) {
140                    if required {
141                        store.observe_labels(graph, Some(kind.default_label_name()))?;
142                    }
143                }
144                store.restored_registry(graph)?.labels()
145            }
146        };
147        Ok(kinds.map(|kind| {
148            labels
149                .iter()
150                .any(|label| label.id == kind.default_label_id())
151        }))
152    }
153    pub fn graph_label_kind(
154        &self,
155        graph: &str,
156        label: &str,
157    ) -> GraphStoreResult<Option<LabelKind>> {
158        match self {
159            Self::Memory(store) => store.graph_label_kind(graph, label),
160            Self::Persistent(store) => store.graph_label_kind(graph, label),
161        }
162    }
163    pub fn create_label(
164        &mut self,
165        graph: &str,
166        label: &str,
167        kind: LabelKind,
168    ) -> GraphStoreResult<Option<u32>> {
169        match self {
170            Self::Memory(store) => store.create_label(graph, label, kind),
171            Self::Persistent(store) => store.create_label(graph, label, kind),
172        }
173    }
174    pub fn drop_label(
175        &mut self,
176        graph: &str,
177        label: &str,
178    ) -> GraphStoreResult<Option<(u32, LabelKind)>> {
179        match self {
180            Self::Memory(store) => store.drop_label(graph, label),
181            Self::Persistent(store) => store.drop_label(graph, label),
182        }
183    }
184    pub fn rename_graph(&mut self, from: &str, to: &str) -> GraphStoreResult<()> {
185        match self {
186            Self::Memory(store) => store.rename_graph(from, to),
187            Self::Persistent(store) => store.rename_graph(from, to),
188        }
189    }
190    pub fn import_label_registry(
191        &mut self,
192        graph: &str,
193        registry: &GraphLabelRegistry,
194    ) -> GraphStoreResult<()> {
195        match self {
196            Self::Memory(store) => {
197                store.import_label_registry(graph, registry);
198                Ok(())
199            }
200            Self::Persistent(store) => store.import_label_registry(graph, registry),
201        }
202    }
203    pub fn rebuild_label_registry_from_ids(&mut self, graph: &str) -> GraphStoreResult<()> {
204        match self {
205            Self::Memory(store) => {
206                store.rebuild_label_registry_from_ids(graph);
207                Ok(())
208            }
209            Self::Persistent(store) => store.rebuild_label_registry_from_ids(graph),
210        }
211    }
212}
213
214impl GraphStore for GraphStoreHandle {
215    fn vertex_id_page(
216        &self,
217        graph: &str,
218        after: Option<u64>,
219        limit: usize,
220    ) -> GraphStoreResult<Vec<u64>> {
221        match self {
222            Self::Memory(store) => store.vertex_id_page(graph, after, limit),
223            Self::Persistent(store) => store.vertex_id_page(graph, after, limit),
224        }
225    }
226    fn edge_id_page(
227        &self,
228        graph: &str,
229        after: Option<u64>,
230        limit: usize,
231    ) -> GraphStoreResult<Vec<u64>> {
232        match self {
233            Self::Memory(store) => store.edge_id_page(graph, after, limit),
234            Self::Persistent(store) => store.edge_id_page(graph, after, limit),
235        }
236    }
237    fn transaction<T>(
238        &mut self,
239        operation: impl FnOnce(&mut Self) -> GraphStoreResult<T>,
240    ) -> GraphStoreResult<T> {
241        match self {
242            Self::Memory(store) => {
243                let backup = store.clone();
244                match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| operation(self))) {
245                    Ok(Ok(value)) => Ok(value),
246                    Ok(Err(error)) => {
247                        *self = Self::Memory(backup);
248                        Err(error)
249                    }
250                    Err(panic) => {
251                        *self = Self::Memory(backup);
252                        std::panic::resume_unwind(panic)
253                    }
254                }
255            }
256            Self::Persistent(store) => {
257                // This clone is a storage handle, never a graph snapshot.
258                let mut checkpoint = store.clone();
259                checkpoint.transaction(|_| operation(self))
260            }
261        }
262    }
263    fn create_graph(&mut self, name: &str) -> GraphStoreResult<()> {
264        match self {
265            Self::Memory(store) => GraphStore::create_graph(store, name),
266            Self::Persistent(store) => GraphStore::create_graph(store, name),
267        }
268    }
269    fn drop_graph(&mut self, name: &str) -> GraphStoreResult<()> {
270        match self {
271            Self::Memory(store) => GraphStore::drop_graph(store, name),
272            Self::Persistent(store) => GraphStore::drop_graph(store, name),
273        }
274    }
275    fn graph_names(&self) -> GraphStoreResult<Vec<String>> {
276        match self {
277            Self::Memory(store) => GraphStore::graph_names(store),
278            Self::Persistent(store) => GraphStore::graph_names(store),
279        }
280    }
281    fn has_graph(&self, name: &str) -> GraphStoreResult<bool> {
282        match self {
283            Self::Memory(store) => GraphStore::has_graph(store, name),
284            Self::Persistent(store) => GraphStore::has_graph(store, name),
285        }
286    }
287    fn union_graphs(&mut self, g1: &str, g2: &str, target: &str) -> GraphStoreResult<()> {
288        match self {
289            Self::Memory(store) => GraphStore::union_graphs(store, g1, g2, target),
290            Self::Persistent(store) => GraphStore::union_graphs(store, g1, g2, target),
291        }
292    }
293    fn intersect_graphs(&mut self, g1: &str, g2: &str, target: &str) -> GraphStoreResult<()> {
294        match self {
295            Self::Memory(store) => GraphStore::intersect_graphs(store, g1, g2, target),
296            Self::Persistent(store) => GraphStore::intersect_graphs(store, g1, g2, target),
297        }
298    }
299    fn difference_graphs(&mut self, g1: &str, g2: &str, target: &str) -> GraphStoreResult<()> {
300        match self {
301            Self::Memory(store) => GraphStore::difference_graphs(store, g1, g2, target),
302            Self::Persistent(store) => GraphStore::difference_graphs(store, g1, g2, target),
303        }
304    }
305    fn copy_graph(&mut self, source: &str, target: &str) -> GraphStoreResult<()> {
306        match self {
307            Self::Memory(store) => GraphStore::copy_graph(store, source, target),
308            Self::Persistent(store) => GraphStore::copy_graph(store, source, target),
309        }
310    }
311    fn add_vertex(&mut self, vertex: Vertex, graph: &str) -> GraphStoreResult<()> {
312        match self {
313            Self::Memory(store) => GraphStore::add_vertex(store, vertex, graph),
314            Self::Persistent(store) => GraphStore::add_vertex(store, vertex, graph),
315        }
316    }
317    fn add_edge(&mut self, edge: Edge, graph: &str) -> GraphStoreResult<()> {
318        match self {
319            Self::Memory(store) => GraphStore::add_edge(store, edge, graph),
320            Self::Persistent(store) => GraphStore::add_edge(store, edge, graph),
321        }
322    }
323    fn remove_vertex(&mut self, vertex_id: u64, graph: &str) -> GraphStoreResult<()> {
324        match self {
325            Self::Memory(store) => GraphStore::remove_vertex(store, vertex_id, graph),
326            Self::Persistent(store) => GraphStore::remove_vertex(store, vertex_id, graph),
327        }
328    }
329    fn remove_edge(&mut self, edge_id: u64, graph: &str) -> GraphStoreResult<()> {
330        match self {
331            Self::Memory(store) => GraphStore::remove_edge(store, edge_id, graph),
332            Self::Persistent(store) => GraphStore::remove_edge(store, edge_id, graph),
333        }
334    }
335    fn neighbors(
336        &self,
337        vertex_id: u64,
338        label: Option<&str>,
339        direction: Direction,
340        graph: &str,
341    ) -> GraphStoreResult<Vec<u64>> {
342        match self {
343            Self::Memory(store) => GraphStore::neighbors(store, vertex_id, label, direction, graph),
344            Self::Persistent(store) => {
345                GraphStore::neighbors(store, vertex_id, label, direction, graph)
346            }
347        }
348    }
349    fn vertices_by_label(&self, label: &str, graph: &str) -> GraphStoreResult<Vec<Vertex>> {
350        match self {
351            Self::Memory(store) => GraphStore::vertices_by_label(store, label, graph),
352            Self::Persistent(store) => GraphStore::vertices_by_label(store, label, graph),
353        }
354    }
355    fn vertex_ids_by_label(&self, label: &str, graph: &str) -> GraphStoreResult<Vec<u64>> {
356        match self {
357            Self::Memory(store) => GraphStore::vertex_ids_by_label(store, label, graph),
358            Self::Persistent(store) => GraphStore::vertex_ids_by_label(store, label, graph),
359        }
360    }
361    fn vertices_in_graph(&self, graph: &str) -> GraphStoreResult<Vec<Vertex>> {
362        match self {
363            Self::Memory(store) => GraphStore::vertices_in_graph(store, graph),
364            Self::Persistent(store) => GraphStore::vertices_in_graph(store, graph),
365        }
366    }
367    fn edges_in_graph(&self, graph: &str) -> GraphStoreResult<Vec<Edge>> {
368        match self {
369            Self::Memory(store) => GraphStore::edges_in_graph(store, graph),
370            Self::Persistent(store) => GraphStore::edges_in_graph(store, graph),
371        }
372    }
373    fn vertex_graphs(&self, vertex_id: u64) -> GraphStoreResult<BTreeSet<String>> {
374        match self {
375            Self::Memory(store) => GraphStore::vertex_graphs(store, vertex_id),
376            Self::Persistent(store) => GraphStore::vertex_graphs(store, vertex_id),
377        }
378    }
379    fn edge_graphs(&self, edge_id: u64) -> GraphStoreResult<BTreeSet<String>> {
380        match self {
381            Self::Memory(store) => store.edge_graphs(edge_id),
382            Self::Persistent(store) => store.edge_graphs(edge_id),
383        }
384    }
385    fn edges_by_label(&self, label: &str, graph: &str) -> GraphStoreResult<Vec<Edge>> {
386        match self {
387            Self::Memory(store) => store.edges_by_label(label, graph),
388            Self::Persistent(store) => store.edges_by_label(label, graph),
389        }
390    }
391    fn out_edge_ids(&self, vertex_id: u64, graph: &str) -> GraphStoreResult<BTreeSet<u64>> {
392        match self {
393            Self::Memory(store) => GraphStore::out_edge_ids(store, vertex_id, graph),
394            Self::Persistent(store) => GraphStore::out_edge_ids(store, vertex_id, graph),
395        }
396    }
397    fn in_edge_ids(&self, vertex_id: u64, graph: &str) -> GraphStoreResult<BTreeSet<u64>> {
398        match self {
399            Self::Memory(store) => GraphStore::in_edge_ids(store, vertex_id, graph),
400            Self::Persistent(store) => GraphStore::in_edge_ids(store, vertex_id, graph),
401        }
402    }
403    fn edge_ids_by_label(&self, label: &str, graph: &str) -> GraphStoreResult<BTreeSet<u64>> {
404        match self {
405            Self::Memory(store) => GraphStore::edge_ids_by_label(store, label, graph),
406            Self::Persistent(store) => GraphStore::edge_ids_by_label(store, label, graph),
407        }
408    }
409    fn vertex_ids_in_graph(&self, graph: &str) -> GraphStoreResult<BTreeSet<u64>> {
410        match self {
411            Self::Memory(store) => GraphStore::vertex_ids_in_graph(store, graph),
412            Self::Persistent(store) => GraphStore::vertex_ids_in_graph(store, graph),
413        }
414    }
415    fn require_vertex_in_graph(&self, vertex_id: u64, graph: &str) -> GraphStoreResult<()> {
416        match self {
417            Self::Memory(store) => GraphStore::require_vertex_in_graph(store, vertex_id, graph),
418            Self::Persistent(store) => GraphStore::require_vertex_in_graph(store, vertex_id, graph),
419        }
420    }
421    fn degree_distribution(&self, graph: &str) -> GraphStoreResult<BTreeMap<u64, u64>> {
422        match self {
423            Self::Memory(store) => GraphStore::degree_distribution(store, graph),
424            Self::Persistent(store) => GraphStore::degree_distribution(store, graph),
425        }
426    }
427    fn label_degree(&self, label: &str, graph: &str) -> GraphStoreResult<f64> {
428        match self {
429            Self::Memory(store) => GraphStore::label_degree(store, label, graph),
430            Self::Persistent(store) => GraphStore::label_degree(store, label, graph),
431        }
432    }
433    fn vertex_label_counts(&self, graph: &str) -> GraphStoreResult<BTreeMap<String, u64>> {
434        match self {
435            Self::Memory(store) => GraphStore::vertex_label_counts(store, graph),
436            Self::Persistent(store) => GraphStore::vertex_label_counts(store, graph),
437        }
438    }
439    fn get_vertex(&self, vertex_id: u64) -> GraphStoreResult<Option<Vertex>> {
440        match self {
441            Self::Memory(store) => GraphStore::get_vertex(store, vertex_id),
442            Self::Persistent(store) => GraphStore::get_vertex(store, vertex_id),
443        }
444    }
445    fn for_each_vertex_borrowed(
446        &self,
447        ids: &[u64],
448        visit: &mut dyn FnMut(u64, Option<&Vertex>) -> bool,
449    ) -> GraphStoreResult<Option<usize>> {
450        match self {
451            Self::Memory(store) => store.for_each_vertex_borrowed(ids, visit),
452            Self::Persistent(store) => store.for_each_vertex_borrowed(ids, visit),
453        }
454    }
455    fn get_edge(&self, edge_id: u64) -> GraphStoreResult<Option<Edge>> {
456        match self {
457            Self::Memory(store) => GraphStore::get_edge(store, edge_id),
458            Self::Persistent(store) => GraphStore::get_edge(store, edge_id),
459        }
460    }
461    fn next_vertex_id(&mut self) -> GraphStoreResult<u64> {
462        match self {
463            Self::Memory(store) => GraphStore::next_vertex_id(store),
464            Self::Persistent(store) => GraphStore::next_vertex_id(store),
465        }
466    }
467    fn next_edge_id(&mut self) -> GraphStoreResult<u64> {
468        match self {
469            Self::Memory(store) => GraphStore::next_edge_id(store),
470            Self::Persistent(store) => GraphStore::next_edge_id(store),
471        }
472    }
473    fn allocate_vertex_id(&mut self, label: &str, graph: &str) -> GraphStoreResult<u64> {
474        match self {
475            Self::Memory(store) => GraphStore::allocate_vertex_id(store, label, graph),
476            Self::Persistent(store) => GraphStore::allocate_vertex_id(store, label, graph),
477        }
478    }
479    fn allocate_edge_id(&mut self, label: &str, graph: &str) -> GraphStoreResult<u64> {
480        match self {
481            Self::Memory(store) => GraphStore::allocate_edge_id(store, label, graph),
482            Self::Persistent(store) => GraphStore::allocate_edge_id(store, label, graph),
483        }
484    }
485    fn clear(&mut self) -> GraphStoreResult<()> {
486        match self {
487            Self::Memory(store) => GraphStore::clear(store),
488            Self::Persistent(store) => GraphStore::clear(store),
489        }
490    }
491    fn vertices(&self) -> GraphStoreResult<BTreeMap<u64, Vertex>> {
492        match self {
493            Self::Memory(store) => GraphStore::vertices(store),
494            Self::Persistent(store) => GraphStore::vertices(store),
495        }
496    }
497    fn edges(&self) -> GraphStoreResult<BTreeMap<u64, Edge>> {
498        match self {
499            Self::Memory(store) => GraphStore::edges(store),
500            Self::Persistent(store) => GraphStore::edges(store),
501        }
502    }
503}