Skip to main content

uqa_execution/catalog/
graph_reads.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Attribute consumed graph catalog projections to the retained query participant.
8
9use super::CatalogReadView;
10use std::{borrow::Cow, sync::Arc};
11use uqa_core::CancellationToken;
12use uqa_graph::{GraphStore, GraphStoreError, GraphStoreHandle};
13use uqa_sql::SQLError;
14use uqa_storage::{
15    catalog::graph_observations::GraphDefinitionKind, mvcc::SerializableReadContext,
16    StorageBackendError,
17};
18
19pub(super) struct GraphCatalogRead {
20    template: GraphStoreHandle,
21    context: SerializableReadContext,
22    cancellation: CancellationToken,
23}
24
25fn graph_error(error: GraphStoreError) -> SQLError {
26    crate::storage_errors::storage_error(
27        "read graph catalog",
28        &StorageBackendError::backend("graph", error),
29    )
30}
31
32impl CatalogReadView {
33    pub(crate) fn metadata_view(&self) -> Cow<'_, Self> {
34        if self.graph_reads.is_none() {
35            return Cow::Borrowed(self);
36        }
37        let mut view = self.clone();
38        view.graph_reads = None;
39        Cow::Owned(view)
40    }
41
42    /// Retain the original participant independently from the catalog's immutable definitions. Binding alone records no reads.
43    pub fn with_graph_reads(
44        mut self,
45        template: GraphStoreHandle,
46        context: SerializableReadContext,
47        cancellation: &CancellationToken,
48    ) -> Self {
49        self.graph_reads = Some(Arc::new(GraphCatalogRead {
50            template: template.with_serializable_read(context.clone(), cancellation),
51            context,
52            cancellation: cancellation.clone(),
53        }));
54        self
55    }
56
57    fn graph_read(&self, name: &str) -> Result<Option<Cow<'_, GraphStoreHandle>>, SQLError> {
58        if let Some(read) = &self.graph_reads {
59            read.template
60                .observe_definition(GraphDefinitionKind::NamedGraph, Some(name))
61                .map_err(graph_error)?;
62        }
63        Ok(self.snapshot.definitions.graphs.get(name).map(|store| {
64            match (&self.graph_reads, store.as_ref()) {
65                (Some(read), GraphStoreHandle::Persistent(store)) => Cow::Owned(
66                    GraphStoreHandle::Persistent(store.clone())
67                        .with_serializable_read(read.context.clone(), &read.cancellation),
68                ),
69                _ => Cow::Borrowed(store.as_ref()),
70            }
71        }))
72    }
73
74    /// Catalog row consumption observes the complete name set, including an empty result.
75    pub fn read_graph_names(&self) -> Result<Vec<String>, SQLError> {
76        self.observe_graph_names()?;
77        Ok(self.graph_names())
78    }
79
80    pub(super) fn observe_graph_names(&self) -> Result<(), SQLError> {
81        if let Some(read) = &self.graph_reads {
82            read.template
83                .observe_definition(GraphDefinitionKind::NamedGraph, None)
84                .map_err(graph_error)?;
85        }
86        Ok(())
87    }
88
89    pub fn graph_labels(
90        &self,
91        graph: &str,
92    ) -> Result<Option<Vec<uqa_graph::GraphLabelInfo>>, SQLError> {
93        self.graph_read(graph)?
94            .map(|store| store.graph_labels(graph))
95            .transpose()
96            .map_err(graph_error)
97    }
98
99    /// Unobserved names for binding and restoration; row consumers use `read_graph_names`.
100    pub fn graph_names(&self) -> Vec<String> {
101        self.snapshot.definitions.graphs.keys().cloned().collect()
102    }
103
104    pub fn graph_next_label_id(&self, graph: &str) -> Result<Option<u32>, SQLError> {
105        self.graph_read(graph)?
106            .map(|store| {
107                store
108                    .label_registry(graph)
109                    .map(|registry| registry.next_label_id)
110            })
111            .transpose()
112            .map_err(graph_error)
113    }
114
115    pub fn graph_label_count(
116        &self,
117        graph: &str,
118        label: &str,
119        kind: uqa_graph::LabelKind,
120    ) -> Result<Option<usize>, SQLError> {
121        self.graph_read(graph)?
122            .map(|store| match kind {
123                uqa_graph::LabelKind::Vertex => store
124                    .vertex_ids_by_label(label, graph)
125                    .map(|identities| identities.len()),
126                uqa_graph::LabelKind::Edge => store
127                    .edge_ids_by_label(label, graph)
128                    .map(|identities| identities.len()),
129            })
130            .transpose()
131            .map_err(graph_error)
132    }
133
134    pub fn graph_vertices(&self, graph: &str) -> Result<Option<Vec<uqa_core::Vertex>>, SQLError> {
135        self.graph_read(graph)?
136            .map(|store| store.vertices_in_graph(graph))
137            .transpose()
138            .map_err(graph_error)
139    }
140
141    pub fn graph_edges(&self, graph: &str) -> Result<Option<Vec<uqa_core::Edge>>, SQLError> {
142        self.graph_read(graph)?
143            .map(|store| store.edges_in_graph(graph))
144            .transpose()
145            .map_err(graph_error)
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn catalog_graph_reads_preserve_cancellation_resource_and_serialization_diagnostics() {
155        let memory = uqa_core::memory::MemoryBudget::new(0)
156            .reserve(1)
157            .unwrap_err();
158        for (error, state) in [
159            (
160                GraphStoreError::from(StorageBackendError::Cancelled(
161                    uqa_core::QueryCancelled::USER_REQUEST,
162                )),
163                "57014",
164            ),
165            (
166                GraphStoreError::from(StorageBackendError::Memory(memory)),
167                "53200",
168            ),
169            (
170                GraphStoreError::SerializationFailure("completed reader".into()),
171                "40001",
172            ),
173        ] {
174            assert_eq!(graph_error(error).sqlstate(), Some(state));
175        }
176    }
177}