drevo_core/engine.rs
1//! [`GraphEngine`] — the graph operations, as a
2//! trait.
3//!
4//! It expresses storage in **graph terms** — nodes, edges, adjacency — and is
5//! what drevo's query layers (Cypher executor, traversal, planner) are written
6//! against. [`NativeGraph`](crate::native::NativeGraph) implements it, and so
7//! does each open transaction, so the same code runs inside or outside one.
8//! The trait is **object-safe** (`&dyn GraphEngine` works) so call sites can
9//! be generic over the engine without monomorphising the whole executor.
10//!
11//! The method set mirrors the core of a store's inherent API — node/edge CRUD
12//! plus adjacency expansion, and the [`crate::engine::GraphEngine::export_dump`]
13//! / [`crate::engine::GraphEngine::apply_dump`] migration seam. Secondary concerns
14//! (FTS, vectors, transactions, statistics) are intentionally out of scope and
15//! layered on above the seam.
16//!
17//! Every method returns [`crate::error::Result`] (i.e. [`crate::error::CoreError`]).
18
19use crate::dump::{Dump, ImportReport};
20use crate::error::Result;
21use std::sync::Arc;
22
23use crate::model::{Direction, Edge, EdgePatch, NewEdge, NewNode, Node, NodePatch};
24
25/// Graph-level storage and traversal, expressed in graph terms: nodes, edges
26/// and adjacency.
27///
28/// Implemented by [`crate::native::NativeGraph`] and by its open transactions,
29/// so code written against the trait runs the same inside or outside a
30/// transaction.
31pub trait GraphEngine {
32 /// Create a node, allocating its id/uuid/timestamps.
33 ///
34 /// # Errors
35 /// Propagates any [`crate::error::CoreError`] from the underlying store
36 /// (e.g. a title-uniqueness violation).
37 fn create_node(&self, new_node: NewNode) -> Result<Node>;
38
39 /// Fetch a node by id, or `Ok(None)` if absent.
40 ///
41 /// # Errors
42 /// Propagates any [`crate::error::CoreError`] from the underlying store.
43 fn get_node(&self, id: u64) -> Result<Option<Arc<Node>>>;
44
45 /// Apply a partial update to a node.
46 ///
47 /// # Errors
48 /// Propagates any [`crate::error::CoreError`] from the underlying store
49 /// (e.g. the node not existing, or a title-uniqueness violation).
50 fn update_node(&self, id: u64, patch: NodePatch) -> Result<Node>;
51
52 /// Delete a node (and its incident edges/indexes).
53 ///
54 /// # Errors
55 /// Propagates any [`crate::error::CoreError`] from the underlying store.
56 fn delete_node(&self, id: u64) -> Result<()>;
57
58 /// Delete many nodes in one batch, returning how many were actually
59 /// removed. Each node is dropped with its incident edges and index
60 /// entries exactly as [`delete_node`](Self::delete_node); ids that are
61 /// already absent are skipped rather than erroring.
62 ///
63 /// The default implementation deletes one at a time (one durable write per
64 /// node). An engine that can batch — the native WAL engine — overrides this
65 /// to flush the whole batch under a **single fsync**, so deleting a subtree
66 /// costs one flush, not `N`.
67 ///
68 /// # Errors
69 /// Propagates any [`crate::error::CoreError`] other than a
70 /// [`NodeNotFound`](crate::error::CoreError::NodeNotFound) for an
71 /// already-absent id.
72 fn delete_nodes(&self, ids: &[u64]) -> Result<usize> {
73 let mut deleted = 0;
74 for &id in ids {
75 match self.delete_node(id) {
76 Ok(()) => deleted += 1,
77 Err(crate::error::CoreError::NodeNotFound(_)) => {}
78 Err(e) => return Err(e),
79 }
80 }
81 Ok(deleted)
82 }
83
84 /// Create an edge between two existing nodes.
85 ///
86 /// # Errors
87 /// Propagates any [`crate::error::CoreError`] from the underlying store.
88 fn create_edge(&self, new_edge: NewEdge) -> Result<Edge>;
89
90 /// Fetch an edge by id, or `Ok(None)` if absent.
91 ///
92 /// # Errors
93 /// Propagates any [`crate::error::CoreError`] from the underlying store.
94 fn get_edge(&self, id: u64) -> Result<Option<Edge>>;
95
96 /// Apply a partial update to an edge (kind / weight / properties).
97 ///
98 /// # Errors
99 /// Propagates any [`crate::error::CoreError`] from the underlying store
100 /// (e.g. the edge not existing, or a non-finite weight).
101 fn update_edge(&self, id: u64, patch: EdgePatch) -> Result<Edge>;
102
103 /// Delete an edge (and its adjacency/index entries).
104 ///
105 /// # Errors
106 /// Propagates any [`crate::error::CoreError`] from the underlying store.
107 fn delete_edge(&self, id: u64) -> Result<()>;
108
109 /// Return the **distinct** node ids adjacent to `node_id` in `direction`,
110 /// optionally restricted to edges of `kind` — the id-only fan-out that reads
111 /// straight from the adjacency index.
112 ///
113 /// # Errors
114 /// Propagates any [`crate::error::CoreError`] from the underlying store.
115 fn neighbor_ids(
116 &self,
117 node_id: u64,
118 direction: Direction,
119 kind: Option<&str>,
120 ) -> Result<Vec<u64>>;
121
122 /// Return the adjacent **nodes** (loaded once each) in `direction`,
123 /// optionally restricted to edges of `kind`.
124 ///
125 /// # Errors
126 /// Propagates any [`crate::error::CoreError`] from the underlying store.
127 fn neighbors(
128 &self,
129 node_id: u64,
130 direction: Direction,
131 kind: Option<&str>,
132 ) -> Result<Vec<Arc<Node>>>;
133
134 /// Return the full [`Edge`] records incident to `node_id` in `direction`
135 /// (the weighted/full-edge expansion, which loads each edge record — unlike
136 /// [`neighbor_ids`](Self::neighbor_ids)).
137 ///
138 /// # Errors
139 /// Propagates any [`crate::error::CoreError`] from the underlying store.
140 fn edges_of(&self, node_id: u64, direction: Direction) -> Result<Vec<Edge>>;
141
142 /// Return **every** node in the store (a full scan — the label-less
143 /// `MATCH (n)`).
144 ///
145 /// # Errors
146 /// Propagates any [`crate::error::CoreError`] from the underlying store.
147 fn all_nodes(&self) -> Result<Vec<Arc<Node>>>;
148
149 /// The number of nodes in the store — the `MATCH (n) RETURN count(*)`
150 /// pushdown target: a bare count needs no record materialisation at all.
151 ///
152 /// The default counts a full [`crate::engine::GraphEngine::all_nodes`]
153 /// scan, which is correct for any engine; implementations with a cheap
154 /// cardinality (such as [`crate::native::NativeGraph`]'s node map)
155 /// override it.
156 ///
157 /// # Errors
158 /// Propagates any [`crate::error::CoreError`] from the underlying store.
159 fn count_nodes(&self) -> Result<u64> {
160 Ok(self.all_nodes()?.len() as u64)
161 }
162
163 /// The number of nodes whose **primary kind** equals `kind` — the
164 /// kind half of the labelled-count pushdown (secondary `_labels`
165 /// matches are the label index's business, not the engine's).
166 ///
167 /// The default counts a full
168 /// [`crate::engine::GraphEngine::nodes_by_kind`] page; engines with a
169 /// kind index override it with the bucket's cardinality.
170 ///
171 /// # Errors
172 /// Propagates any [`crate::error::CoreError`] from the underlying store.
173 fn count_nodes_by_kind(&self, kind: &str) -> Result<u64> {
174 Ok(self.nodes_by_kind(kind, usize::MAX, 0)?.len() as u64)
175 }
176
177 /// Return **every** edge in the store (a full scan — the anonymous
178 /// `MATCH ()-[r]->()`).
179 ///
180 /// # Errors
181 /// Propagates any [`crate::error::CoreError`] from the underlying store.
182 fn all_edges(&self) -> Result<Vec<Edge>>;
183
184 /// Return nodes of a given `kind` (label scan), paginated by `limit` /
185 /// `offset`.
186 ///
187 /// # Errors
188 /// Propagates any [`crate::error::CoreError`] from the underlying store.
189 fn nodes_by_kind(&self, kind: &str, limit: usize, offset: usize) -> Result<Vec<Arc<Node>>>;
190
191 /// Export the entire graph as a `drevo-json-v1` [`Dump`] — every node and
192 /// edge plus the id-allocation counters — the interchange format used for
193 /// backup, JSON/GraphML round-trips, and cross-engine migration.
194 ///
195 /// This is the read half of the migration seam:
196 /// `dst.apply_dump(src.export_dump()?)` moves a live graph between any two
197 /// engines.
198 ///
199 /// # Errors
200 /// Propagates any [`crate::error::CoreError`] from the underlying store.
201 fn export_dump(&self) -> Result<Dump>;
202
203 /// Bulk-load a [`Dump`] into this engine **verbatim**, preserving every
204 /// node/edge id (so edges stay connected) and clamping the id counters above
205 /// every imported id. Nodes/edges already present byte-for-byte are skipped
206 /// (idempotent re-import); an id that collides with *different* content, or
207 /// an edge whose endpoint is missing, is an error.
208 ///
209 /// This is the write half of the migration seam. The counts in the returned
210 /// [`ImportReport`] separate freshly-inserted from skipped rows.
211 ///
212 /// # Errors
213 /// * [`crate::error::CoreError::NodeNotFound`] — an edge references an
214 /// endpoint that neither exists nor is supplied by the dump.
215 /// * Other [`crate::error::CoreError`] variants — an id collision against
216 /// different content, a title/uuid clash, or a backend failure.
217 fn apply_dump(&self, dump: Dump) -> Result<ImportReport>;
218}